Copyright © 1997, 1998, 1999, 2000 by the PHP Documentation Group
Copyright
This manual is © Copyright 1997, 1998, 1999, 2000 by the PHP Documentation Group. The members of this group are listed on the front page of this manual.
This manual can be redistributed 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.
PHP, which stands for "PHP: Hypertext Preprocessor", is an HTML-embedded scripting language. Much of its syntax is borrowed from C, Java and Perl with a couple of unique PHP-specific features thrown in. The goal of the language is to allow web developers to write dynamically generated pages quickly.
This manual is written in XML using the DocBook XML DTD, using DSSSL (Document Style and Semantics Specification Language) for formatting. The tools used for formatting HTML, TeX and RTF versions are Jade, written by James Clark and The Modular DocBook Stylesheets written by Norman Walsh. PHP's documentation framework is maintained by Stig Sζther Bakken.
Daily HTML snapshots of the manual, including translations, can be found at http://snaps.php.net/manual/.
PHP (officially "PHP: Hypertext Preprocessor") is a server-side HTML-embedded scripting language.
Simple answer, but what does that mean? An example:
Example 1-1. An introductory example
|
Notice how this is different from a CGI script written in other languages like Perl or C -- instead of writing a program with lots of commands to output HTML, you write an HTML script with a some embedded code to do something (in this case, output some text). The PHP code is enclosed in special start and end tags that allow you to jump into and out of PHP mode.
What distinguishes PHP from something like client-side Javascript is that the code is executed on the server. If you were to have a script similar to the above on your server, the client would receive the results of running that script, with no way of determining what the underlying code may be. You can even configure your web server to process all your HTML files with PHP, and then there's really no way that users can tell what you have up your sleeve.
At the most basic level, PHP can do anything any other CGI program can do, such as collect form data, generate dynamic page content, or send and receive cookies.
Perhaps the strongest and most significant feature in PHP is its support for a wide range of databases. Writing a database-enabled web page is incredibly simple. The following databases are currently supported:
Adabas D InterBase PostgreSQL dBase FrontBase Solid Empress mSQL Sybase FilePro (read-only) Direct MS-SQL Velocis IBM DB2 MySQL Unix dbm Informix ODBC Ingres Oracle (OCI7 and OCI8)
PHP also has support for talking to other services using protocols such as IMAP, SNMP, NNTP, POP3, HTTP and countless others. You can also open raw network sockets and interact using other protocols.
PHP was conceived sometime in the fall of 1994 by Rasmus Lerdorf. Early non-released versions were used on his home page to keep track of who was looking at his online resume. The first version used by others was available sometime in early 1995 and was known as the Personal Home Page Tools. It consisted of a very simplistic parser engine that only understood a few special macros and a number of utilities that were in common use on home pages back then. A guestbook, a counter and some other stuff. The parser was rewritten in mid-1995 and named PHP/FI Version 2. The FI came from another package Rasmus had written which interpreted html form data. He combined the Personal Home Page tools scripts with the Form Interpreter and added mSQL support and PHP/FI was born. PHP/FI grew at an amazing pace and people started contributing code to it.
It is difficult to give any hard statistics, but it is estimated that by late 1996 PHP/FI was in use on at least 15,000 web sites around the world. By mid-1997 this number had grown to over 50,000. Mid-1997 also saw a change in the development of PHP. It changed from being Rasmus' own pet project that a handful of people had contributed to, to being a much more organized team effort. The parser was rewritten from scratch by Zeev Suraski and Andi Gutmans and this new parser formed the basis for PHP Version 3. A lot of the utility code from PHP/FI was ported over to PHP3 and a lot of it was completely rewritten.
Today (end-1999) either PHP/FI or PHP3 ships with a number of commercial products such as C2's StrongHold web server and RedHat Linux. A conservative estimate based on an extrapolation from numbers provided by NetCraft (see also Netcraft Web Server Survey) would be that PHP is in use on over 1,000,000 sites around the world. To put that in perspective, that is more sites than run Netscape's flagship Enterprise server on the Internet.
Also as of this writing, work is underway on the next generation of PHP, which will utilize the powerful Zend scripting engine to deliver higher performance, and will also support running under webservers other than Apache as a native server module.
The source code, and binary distributions for some platforms (including Windows), can be found at http://www.php.net/.
This section will guide you through the configuration and installation of PHP. Prerequisite knowledge and software:
Basic UNIX skills (being able to operate "make" and a C compiler)
An ANSI C compiler
A web server
1. gunzip apache_1.3.x.tar.gz 2. tar xvf apache_1.3.x.tar 3. gunzip php-x.x.x.tar.gz 4. tar xvf php-x.x.x.tar 5. cd apache_1.3.x 6. ./configure --prefix=/www 7. cd ../php-x.x.x 8. ./configure --with-mysql --with-apache=../apache_1.3.x --enable-track-vars 9. make 10. make install 11. cd ../apache_1.3.x 12. for PHP 3: ./configure --activate-module=src/modules/php3/libphp3.a for PHP 4: ./configure --activate-module=src/modules/php4/libphp4.a 13. make 14. make install Instead of this step you may prefer to simply copy the httpd binary overtop of your existing binary. Make sure you shut down your server first though. 15. cd ../php-x.x.x 16. for PHP 3: cp php3.ini-dist /usr/local/lib/php3.ini for PHP 4: cp php.ini-dist /usr/local/lib/php.ini You can edit your .ini file to set PHP options. If you prefer this file in another location, use --with-config-file-path=/path in step 8. 17. Edit your httpd.conf or srm.conf file and add: For PHP 3: AddType application/x-httpd-php3 .php3 For PHP 4: AddType application/x-httpd-php .php You can choose any extension you wish here. .php is simply the one we suggest. 18. Use your normal procedure for starting the Apache server. (You must stop and restart the server, not just cause the server to reload by use a HUP or USR1 signal.) |
PHP can be compiled in a number of different ways. Here is a quick summary:
./configure --with-apxs --with-pgsql |
This will create a libphp4.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 libphp4.so library.
./configure --with-apxs --with-pgsql=shared |
This will again create a libphp4.so shared library for Apache, but it will also create a pgsql.so shared library that is loaded into PHP either by using the extension directive in php.ini file or by loading it explicitly in a script using the dl() function.
./configure --with-apache=/path/to/apache_source --with-pgsql |
This will create a libmodphp4.a library, a mod_php4.c and some accompanying files and copy this into the src/modules/php4 directory in the Apache source tree. Then you compile Apache using --activate-module=src/modules/php4/libphp4.a and the Apache build system will create libphp4.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 eihter the php.ini file or directly using dl().
To build PHP as an fhttpd module, answer "yes" to "Build as an fhttpd module?" (the --with-fhttpd=DIR option to configure) and specify the fhttpd source base directory. The default directory is /usr/local/src/fhttpd. If you are running fhttpd, building PHP as a module will give better performance, more control and remote execution capability.
The default is to build PHP as a CGI program. If you are running a web server PHP has module support for, you should generally go for that solution for performance reasons. However, the CGI version enables Apache users to run different PHP-enabled pages under different user-ids. Please make sure you read through the Security chapter if you are going to run PHP as a CGI.
PHP has native support for a number of databases (as well as ODBC):
--with-adabas=DIR |
Enables Adabas D support. The parameter is the Adabas D install directory and defaults to /usr/local/adabasd.
--with-filepro |
Enables the bundled read-only filePro support. No external libraries are required.
--with-ibm-db2=DIR |
Enables IBM DB2 support. The parameter to this option is the DB2 base install directory and defaults to /home/db2inst1/sqllib.
--with-msql=DIR |
Enables mSQL support. The parameter to this option is the mSQL install directory and defaults to /usr/local/Hughes. This is the default directory of the mSQL 2.0 distribution. configure automatically detects which mSQL version you are running and PHP supports both 1.0 and 2.0, but if you compile PHP with mSQL 1.0, you can only access mSQL 1.0 databases, and vice-versa.
See also mSQL Configuration Directives in the configuration file.
--with-mysql=DIR |
Enables MySQL support. The parameter to this option is the MySQL install directory and defaults to /usr/local. This is the default installation directory of the MySQL distribution.
See also MySQL Configuration Directives in the configuration file.
--with-iodbc=DIR |
Includes iODBC support. This feature was first developed for iODBC Driver Manager, a freely redistributable ODBC driver manager which runs under many flavors of UNIX. The parameter to this option is the iODBC installation directory and defaults to /usr/local.
--with-openlink=DIR |
Includes OpenLink ODBC support. The parameter to this option is the OpenLink ODBC installation directory and defaults to /usr/local/openlink.
--with-oracle=DIR |
Includes Oracle support. Has been tested and should be working at least with Oracle versions 7.0 through 7.3. The parameter is the ORACLE_HOME directory. You do not have to specify this parameter if your Oracle environment has been set up.
--with-pgsql=DIR |
Includes PostgreSQL support. The parameter is the PostgreSQL base install directory and defaults to /usr/local/pgsql.
See also Postgres Configuration Directives in the configuration file.
--with-solid=DIR |
Includes Solid support. The parameter is the Solid install directory and defaults to /usr/local/solid.
--with-sybase=DIR |
Includes Sybase support. The parameter is the Sybase install directory and defaults to /home/sybase.
See also Sybase Configuration Directives in the configuration file.
--with-sybase-ct=DIR |
Includes Sybase-CT support. The parameter is the Sybase-CT install directory and defaults to /home/sybase.
See also Sybase-CT Configuration Directives in the configuration file.
--with-velocis=DIR |
Includes Velocis support. The parameter is the Velocis install directory and defaults to /usr/local/velocis.
--with-custom-odbc=DIR |
Includes support for an arbitrary custom ODBC library. The parameter is the base directory and defaults to /usr/local.
This option implies that you have defined CUSTOM_ODBC_LIBS when you run the configure script. You also must have a valid odbc.h header somewhere in your include path. If you don't have one, create it and include your specific header from there. Your header may also require some extra definitions, particularly when it is multiplatform. Define them in CFLAGS.
For example, you can use Sybase SQL Anywhere on QNX as following: CFLAGS=-DODBC_QNX LDFLAGS=-lunix CUSTOM_ODBC_LIBS="-ldblib -lodbc" ./configure --with-custom-odbc=/usr/lib/sqlany50
--disable-unified-odbc |
Disables the Unified ODBC module, which is a common interface to all the databases with ODBC-based interfaces, such as Solid, IBM DB2 and Adabas D. It also works for normal ODBC libraries. Has been tested with iODBC, Solid, Adabas D, IBM DB2 and Sybase SQL Anywhere. Requires that one (and only one) of these modules or the Velocis module is enabled, or a custom ODBC library specified. This option is only applicable if one of the following options is used: --with-iodbc, --with-solid, --with-ibm-db2, --with-adabas, --with-velocis, or --with-custom-odbc.
See also Unified ODBC Configuration Directives in the configuration file.
--with-mcrypt |
Include support for the mcrypt library. See the mcrypt documentation for more information. If you use the optional DIR argument, PHP will look for mcrypt.h in DIR/include.
--enable-sysvsem |
Include support for Sys V semaphores (supported by most Unix derivates). See the Semaphore and Shared Memory documentation for more information.
--enable-sysvshm |
Include support for Sys V shared memory (supported by most Unix derivates). See the Semaphore and Shared Memory documentation for more information.
--with-xml |
Include support for a non-validating XML parser using James Clark's expat library. See the XML function reference for details.
--enable-maintainer-mode |
Turns on extra dependencies and compiler warnings used by some of the PHP developers.
--with-system-regex |
Uses the system's regular expression library rather than the bundled one. If you are building PHP as a server module, you must use the same library when building PHP as when linking the server. Enable this if the system's library provides special features you need. It is recommended that you use the bundled library if possible.
--with-config-file-path=DIR |
The path used to look for the configuration file when PHP starts up.
--with-exec-dir=DIR |
Only allow running of executables in DIR when in safe mode. Defaults to /usr/local/bin. This option only sets the default, it may be changed with the safe_mode_exec_dir directive in the configuration file later.
--enable-debug |
Enables extra debug information. This makes it possible to gather more detailed information when there are problems with PHP. (Note that this doesn't have anything to do with debugging facilities or information available to PHP scripts.)
--enable-safe-mode |
Enables "safe mode" by default. This imposes several restrictions on what PHP can do, such as opening only files within the document root. Read the Security chapter for more more information. CGI users should always enable secure mode. This option only sets the default, it may be enabled or disabled with the safe_mode directive in the configuration file later.
--enable-track-vars |
Makes PHP keep track of where GET/POST/cookie variables come from in the arrays HTTP_GET_VARS, HTTP_POST_VARS and HTTP_COOKIE_VARS. This option only sets the default, it may be enabled or disabled with the track_vars directive in the configuration file later.
--enable-magic-quotes |
Enable magic quotes by default. This option only sets the default, it may be enabled or disabled with the magic_quotes_runtime directive in the configuration file later. See also the magic_quotes_gpc and the magic_quotes_sybase directives.
--enable-debugger |
Enables the internal PHP debugger support. This feature is still in an experimental state. See also the Debugger Configuration directives in the configuration file.
--enable-discard-path |
If this is enabled, the PHP CGI binary can safely be placed outside of the web tree and people will not be able to circumvent .htaccess security. Read the section in the security chapter about this option.
--enable-bcmath |
Enables bc style arbitrary precision math functions. See also the bcmath.scale option in the configuration file.
--enable-force-cgi-redirect |
Enable the security check for internal server redirects. You should use this if you are running the CGI version with Apache.
When using PHP as a CGI binary, PHP by default always first checks that it is used by redirection (for example under Apache, by using Action directives). This makes sure that the PHP binary cannot be used to bypass standard web server authentication procedures by calling it directly, like http://my.host/cgi-bin/php/secret/doc.html. This example accesses http://my.host/secret/doc.html but does not honour any security settings enforced by httpd for directory /secret.
Not enabling option disables the check and enables bypassing httpd security and authentication settings. Do this only if your server software is unable to indicate that a safe redirection was done and all your files under your document root and user directories may be accessed by anyone.
Read the section in the security chapter about this option.
--disable-short-tags |
Disables the short form <? ?> PHP tags. You must disable the short form if you want to use PHP with XML. With short tags disabled, the only PHP code tag is <?php ?>. This option only sets the default, it may be enabled or disabled with the short_open_tag directive in the configuration file later.
--enable-url-includes |
Makes it possible to run code on other HTTP or FTP servers directly from PHP with include(). See also the include_path option in the configuration file.
To make the PHP installation look for header or library files in different directories, modify the CPPFLAGS and LDFLAGS environment variables, respectively. If you are using a sensible shell, you should be able to do LDFLAGS=-L/my/lib/dir CPPFLAGS=-I/my/include/dir ./configure
When PHP is configured, you are ready to build the CGI executable or the PHP library. The command make should take care of this. If it fails and you can't figure out why, see the Problems section.
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.
If you have built PHP as a CGI program, you may benchmark your build by typing make bench. Note that if safe mode is on by default, the benchmark may not be able to finish if it takes longer then the 30 seconds allowed. This is because the set_time_limit() can not be used in safe mode. Use the max_execution_time configuration setting to control this time for your own scripts. make bench ignores the configuration file.
This install guide will help you install and configure PHP on your Windows 9x/NT webservers. This guide was compiled by Bob Silva. The latest revision can be found at http://www.umesd.k12.or.us/php/win32install.html.
This guide provides installation support for:
Personal Web Server (Newest version recommended)
Internet Information Server 3 or 4
Apache 1.3.x
Omni HTTPd 2.0b1
The following steps should be performed on all installations before the server specific instructions.
Extract the distribution file to a directory of your choice. "C:\PHP\" is a good start.
Copy the file, 'php.ini-dist' to your '%WINDOWS%' directory and rename it to 'php.ini'. Your '%WINDOWS%' directory is typically:
c:\windows for Windows 95/98 |
c:\winnt or c:\winnt40 for NT servers |
Edit your 'php.ini' file:
You will need to change the 'extension_dir' setting to point to your php-install-dir, or where you have placed your 'php_*.dll' files. ex: c:\php
If you are using Omni Httpd, do not follow the next step. Set the 'doc_root' to point to your webservers document_root. ex: c:\apache\htdocs or c:\webroot
Choose which modules you would like to load when PHP starts. You can uncomment the: 'extension=php_*.dll' lines to load these modules. Some modules require you to have additional libraries installed on your system for the module to work correctly. The PHP FAQ has more information on where to get supporting libraries. You can also load a module dynamically in your script using: dl("php_*.dll");
On PWS and IIS, you can set the browscap.ini to point to: 'c:\windows\system\inetsrv\browscap.ini' on Windows 95/98 and 'c:\winnt\system32\inetsrv\browscap.ini' on NT Server. Additional information on using the browscap functionality in PHP can be found at this mirror, select the "source" button to see it in action.
The DLLs for PHP extensions are prefixed with 'php_'. This prevents confusion between PHP extensions and their supporting libraries.
The recommended method for configuring these servers is to use the INF file included with the distribution (php_iis_reg.inf). You may want to edit this file and make sure the extensions and PHP install directories match your configuration. Or you can follow the steps below to do it manually.
WARNING: These steps involve working directly with the windows registry. One error here can leave your system in an unstable state. We highly recommend that you back up your registry first. The PHP Development team will not be held responsible if you damage your registry.
Run Regedit.
Navigate to: HKEY_LOCAL_MACHINE /System /CurrentControlSet /Services /W3Svc /Parameters /ScriptMap.
On the edit menu select: New->String Value.
Type in the extension you wish to use for your php scripts. ex: .php
Double click on the new string value and enter the path to php.exe in the value data field. ex: c:\php\php.exe %s %s. The '%s %s' is VERY important, PHP will not work properly without it.
Repeat these steps for each extension you wish to associate with PHP scripts.
Now navigate to: HKEY_CLASSES_ROOT
On the edit menu select: New->Key.
Name the key to the extension you setup in the previous section. ex: .php
Highlight the new key and in the right side pane, double click the "default value" and enter phpfile.
Repeat the last step for each extension you set up in the previous section.
Now create another New->Key under HKEY_CLASSES_ROOT and name it phpfile.
Highlight the new key phpfile and in the right side pane, double click the "default value" and enter PHP Script.
Right click on the phpfile key and select New->Key, name it Shell.
Right click on the Shell key and select New->Key, name it open.
Right click on the open key and select New->Key, name it command.
Highlight the new key command and in the right side pane, double click the "default value" and enter the path to php.exe. ex: c:\php\php.exe -q %1. (don't forget the %1).
Exit Regedit.
PWS and IIS 3 users now have a fully operational system. IIS 3 users can use a nifty tool from Steven Genusa to configure their script maps.
To install PHP on an NT Server running IIS 4, follow these instructions:
In Internet Service Manager (MMC), select the Web site or the starting point directory of an application.
Open the directory's property sheets (by right clicking and selecting properties), and then click the Home Directory, Virtual Directory, or Directory tab.
Click the Configuration button, and then click the App Mappings tab.
Click Add, and in the Executable box, type: c:\path-to-php-dir\php.exe %s %s. You MUST have the %s %s on the end, PHP will not function properly if you fail to do this.
In the Extension box, type the file name extension you want associated with PHP scripts. (You must repeat step 5 and 6 for each extension you want accociated with PHP scripts. (.php and .phtml are common.)
Set up the appropriate security. (This is done in Internet Service Manager), and if your NT Server uses NTFS file system, add execute rights for I_USR_ to the directory that contains php.exe.
You must edit your srm.conf or httpd.conf to configure Apache to work with the PHP CGI binary.
Although there can be a few variations of configuring PHP under Apache, this one is simple enough to be used by the newcomer. Please consult the Apache Docs for further configuration directives.
ScriptAlias /php/ "c:/path-to-php-dir/"
AddType application/x-httpd-php .php
AddType application/x-httpd-php .phtml
Action application/x-httpd-php "/php/php.exe"
To use the source code highlighting feature, simply create a PHP script file and stick this code in: <?php show_source ("original_php_script.php"); ?>. Substitute original_php_script.php with the name of the file you wish to show the source of. (this is only one way of doing it). Note: On Win-Apache all back slashes in a path statement such as: "c:\directory\file.ext", must be converted to forward slashes.
This has got to be the easiest config there is:
Step 1: Install Omni server
Step 2: Right click on the blue OmniHTTPd icon in the system tray and select Properties
Step 3: Click on Web Server Global Settings
Step 4: On the 'External' tab, enter: virtual = .php | actual = c:\path-to-php-dir\php.exe
Step 5: On the Mime tab, enter: virtual = wwwserver/stdcgi | actual = .php
Step 6: Click OK
Repeat steps 2 - 6 for each extension you want to associate with PHP.
Table 2-1. PHP Modules
php_calendar.dll | Calendar conversion functions |
php_crypt.dll | Crypt functions |
php_dbase.dll | DBase functions |
php_dbm.dll | GDBM emulation via Berkely DB2 library |
php_filepro.dll | READ ONLY access to filepro databases |
php_gd.dll | GD Library functions for gif manipulation |
php_hyperwave.dll | HyperWave functions |
php_imap4r2.dll | IMAP 4 functions |
php_ldap.dll | LDAP functions |
php_msql1.dll | mSQL 1 client |
php_msql2.dll | mSQL 2 client |
php_mssql.dll | MSSQL client (requires MSSQL DB-Libraries |
php3_mysql.dll (Built into PHP 4) | MySQL functions |
php_nsmail.dll | Netscape mail functions |
php_oci73.dll | Oracle functions |
php_snmp.dll | SNMP get and walk functions (NT only!) |
php_zlib.dll | ZLib functions |
Some problems are more common than others. The most common ones are listed in the PHP FAQ, found at http://www.php.net/FAQ.php
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://www.php.net/bugs.php.
If you are still stuck, someone on the PHP 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/. To subscribe to the PHP mailing list, send an empty mail to php-general-subscribe@lists.php.net. The mailing list address is php-general@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, etc.), and preferably enough code to make others able to reproduce and test your problem.
The configuration file (called php3.ini in PHP 3.0, and simply php.ini as of PHP 4.0) 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 version, it happens on every invocation.
When using PHP as an Apache module, you can also change the configuration settings using directives in Apache configuration files and .htaccess files.
With PHP 3.0, there are Apache directives that correspond to each configuration setting in the php3.ini name, except the name is prefixed by "php3_".
With PHP 4.0, there are just a few Apache directives that allow you to change the PHP configuration settings.
This sets the value of the specified variable.
This is used to set a Boolean configuration option.
This sets the value of the specified variable. "Admin" configuration settings can only be set from within the main Apache configuration files, and not from .htaccess files.
This is used to set a Boolean configuration option.
You can view the settings of the configuration values in the output of phpinfo(). You can also access the values of individial configuration settings using get_cfg_var().
Enables the use of ASP-like <% %> tags in addition to the usual <?php ?> tags. This includes the variable-value printing shorthand of <%= $value %>. For more information, see Escaping from HTML.
Note: Support for ASP-style tags was added in 3.0.4.
Specifies the name of a file that is automatically parsed after the main file. The file is included as if it was called with the include() function, so include_path is used.
The special value none disables auto-appending.
Note: If the script is terminated with exit(), auto-append will not occur.
Specifies the name of a file that is automatically parsed before the main file. The file is included as if it was called with the include() function, so include_path is used.
The special value none disables auto-prepending.
This determines whether errors should be printed to the screen as part of the HTML output or not.
PHP's "root directory" on the server. Only used if non-empty. If PHP is configured with safe mode, no files outside this directory are served.
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.
Name of file where script errors should be logged. 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.
Set the error reporting level. The parameter is an integer representing a bit field. Add the values of the error reporting levels you want.
Table 3-1. Error Reporting Levels
bit value | enabled reporting |
---|---|
1 | normal errors |
2 | normal warnings |
4 | parser errors |
8 | non-critical style-related warnings |
Limit the files that can be opened by PHP to the specified directory-tree.
When a script tries to open a file with, for example, fopen or gzopen, the location of the file is checked. When the file is outside the specified directory-tree, PHP will refuse to open it. All symbolic links are resolved, so it's not possible to avoid this restriction with a symlink.
The special value . indicates that the directory in which the script is stored will be used as base-directory.
Under Windows, separate the directories with a semicolon. On all other systems, separate the directories with a colon. As an Apache module, open_basedir paths from parent directories are now automatically inherited.
Note: Support for multiple directories was added in 3.0.7.
The default is to allow all files to be opened.
Set the order of GET/POST/COOKIE variable parsing. The default setting of this directive is "GPC". Setting this to "GP", for example, will cause PHP to completely ignore cookies and to overwrite any GET method variables with POST-method variables of the same name.
On by default. If changed to Off scripts will be terminated as soon as they try to output something after a client has aborted their connection. ignore_user_abort().
Specifies a list of directories where the require(), include() and fopen_with_path() functions look for files. The format is like the system's PATH environment variable: a list of directories separated with a colon in UNIX or semicolon in Windows.
Example 3-1. UNIX include_path
|
Example 3-2. Windows include_path
|
Tells whether script error messages should be logged to the server's error log. This option is thus server-specific.
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. If magic_quotes_sybase is also on, a single-quote is escaped with a single-quote instead of a backslash.
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.
If magic_quotes_sybase is also on, a single-quote is escaped with a single-quote instead of a backslash if magic_quotes_gpc or magic_quotes_runtime is enabled.
This sets the maximum time in seconds a script is allowed to take before it is terminated by the parser. This helps prevent poorly written scripts from tieing up the server.
This sets the maximum amount of memory in bytes that a script is allowed to allocate. This helps prevent poorly written scripts for eating up all available memory on a server.
Tells whether the short form (<? ?>of PHP's open tag should be allowed. If you want to use PHP in combination with XML, you have to disable this option. If disabled, you must use the long form of the open tag (<?php ?>).
If enabled, the last error message will always be present in the global variable $php_errormsg.
If enabled, GET, POST and cookie input can be found in the global associative arrays $HTTP_GET_VARS, $HTTP_POST_VARS and $HTTP_COOKIE_VARS, respectively.
The temporary directory used for storing files when doing file upload. Must be writable by whatever user PHP is running as.
The base name of the directory used on a user's home directory for PHP files, for example public_html.
If enabled, this option makes PHP output a warning when the plus (+) operator is used on strings. This is to make it easier to find scripts that need to be rewritten to using the string concatenator instead (.).
DNS name or IP address of the SMTP server PHP under Windows should use for mail sent with the mail() function.
Which "From:" mail address should be used in mail sent from PHP under Windows.
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.
Whether to enable PHP's safe mode. Read the Security chapter for more more information.
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.
DNS name or IP address of host used by the debugger.
Port number used by the debugger.
Whether the debugger is enabled.
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 the safe_mode and open_basedir restrictions.
The default is to allow dynamic loading, except when using safe-mode. In safe-mode, it's always imposible to use dl().
In what directory PHP should look for dynamically loadable extensions.
Which dynamically loadable extensions to load when PHP starts up.
Whether to allow persistent MySQL connections.
The default server host to use when connecting to the database server if no other host is specified.
The default user name to use when connecting to the database server if no other name is specified.
The default password to use when connecting to the database server if no other password is specified.
The maximum number of persistent MySQL connections per process.
The maximum number of MySQL connections per process, including persistent connections.
Whether to allow persistent mSQL connections.
The maximum number of persistent mSQL connections per process.
The maximum number of mSQL connections per process, including persistent connections.
Whether to allow persistent Postgres connections.
The maximum number of persistent Postgres connections per process.
The maximum number of Postgres connections per process, including persistent connections.
Whether to allow persistent Sybase connections.
The maximum number of persistent Sybase connections per process.
The maximum number of Sybase connections per process, including persistent connections.
Whether to allow persistent Sybase-CT connections. The default is on.
The maximum number of persistent Sybase-CT connections per process. The default is -1 meaning unlimited.
The maximum number of Sybase-CT connections per process, including persistent connections. The default is -1 meaning unlimited.
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.
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.
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.
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 am operation times out, your script will be terminated before it can take action on failure. The default is no limit.
The name of the host you claim to be connecting from, for display by sp_who. The default is none.
Whether to allow persistent Informix connections.
The maximum number of persistent Informix connections per process.
The maximum number of Informix connections per process, including persistent connections.
The default host to connect to when no host is specified in ifx_connect() or ifx_pconnect().
The default user id to use when none is specified in ifx_connect() or ifx_pconnect().
The default password to use when none is specified in ifx_connect() or ifx_pconnect().
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().
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().
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().
Set to true if you want to trim trailing spaces from CHAR columns when fetching them.
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().
Number of decimal digits for all bcmath functions.
Name of browser capabilities file. See also get_browser().
ODBC data source to use if none is specified in odbc_connect() or odbc_pconnect().
User name to use if none is specified in odbc_connect() or odbc_pconnect().
Password to use if none is specified in odbc_connect() or odbc_pconnect().
Whether to allow persistent ODBC connections.
The maximum number of persistent ODBC connections per process.
The maximum number of ODBC connections per process, including persistent connections.
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 it gives 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. This chapter explains the different configuration option combinations and the situations they can be safely used.
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.php3 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.php3. Unfortunately, if the request is originally given in this form, no access checks are made by web server for file /secret/script.php3, but only for the /cgi-bin/php file. This way any user able to access /cgi-bin/php is able to access any protected document on the web server.
In PHP, compile-time configuration option --enable-force-cgi-redirect and runtime configuration directives doc_root and user_dir can be used to prevent this attack, if the server document tree has any directories with access restrictions. See below for full the explanation of the different combinations.
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 --disable-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.php3 nor by redirection http://my.host/dir/script.php3.
Redirection can be configured in Apache by using AddHandler and Action directives (see below).
This compile-time option prevents anyone from calling PHP directly with a url like http://my.host/cgi-bin/php/secretdir/script.php3. Instead, PHP will only parse in this mode if it has gone through a web server redirect rule.
Usually the redirection in the Apache configuration is done with the following directives:
Action php3-script /cgi-bin/php AddHandler php3-script .php3 |
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.
To include active content, like scripts and executables, in the web server document directories is sometimes consider 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 an url like http://my.host/~user/doc.php3 does not result in opening a file under users home directory, but a file called ~user/doc.php3 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.php3 will open a file called doc.php3 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.php3.
user_dir expansion happens regardless of the doc_root setting, so you can control the document root and user directory access separately.
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 |
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.
When PHP is used as an Apache module it inherits Apache's user permissions (typically those of the "nobody" user).
There are four ways of escaping from HTML and entering "PHP code mode":
Example 5-1. Ways of escaping from HTML
|
The first way is only available if short tags have been enabled. This can be done via the short_tags() function, by enabling the short_open_tag configuration setting in the PHP config file, or by compiling PHP with the --enable-short-tags option to configure.
The fourth way is only available if ASP-style tags have been enabled using the asp_tags configuration setting.
Note: Support for ASP-style tags was added in 3.0.4.
The closing tag for the block will include the immediately trailing newline if one is present.
Instructions are separated the same as in C or perl - terminate each statement with a semicolon.
The closing tag (?>) also implies the end of the statement, so the following are equivalent:
<?php echo "This is a test"; ?> <?php echo "This is a test" ?> |
PHP supports 'C', 'C++' and Unix shell-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 shell-style style comment ?> |
The "one-line" comment styles actually only comment to the end of the line or the current block of PHP code, whichever comes first.
<h1>This is an <?# echo "simple";?> example.</h1> <p>The header above will say 'This is an example'. |
You should be careful not to nest 'C' style comments, which can happen when commenting out large blocks.
<?php /* echo "This is a test"; /* This comment will cause a problem */ */ ?> |
PHP supports the following types:
The type of a variable is usually not set by the programmer; rather, it is decided at runtime by PHP depending on the context in which that variable is used.
If you would like to force a variable to be converted to a certain type, you may either cast the variable or use the settype() function on it.
Note that a variable may behave in different manners in certain situations, depending on what type it is at the time. For more information, see the section on Type Juggling.
Integers can be specified using any of the following syntaxes:
$a = 1234; # decimal number $a = -123; # a negative number $a = 0123; # octal number (equivalent to 83 decimal) $a = 0x12; # hexadecimal number (equivalent to 18 decimal) |
Floating point numbers ("doubles") can be specified using any of the following syntaxes:
$a = 1.234; $a = 1.2e3; |
Warning |
It is quite usual that simple decimal fractions like 0.1 or 0.7 cannot be converted into their internal binary counterparts without a little loss of precision. This can lead to confusing results: for example, floor((0.1+0.7)*10) will usually return 7 instead of the expected 8 as the result of the internal representation really being something like 7.9999999999.... This is related to the fact that it is impossible to exactly express some fractions in decimal notation with a finite number of digits. For instance, 1/3 in decimal form becomes 0.3333333. . .. So never trust floating number results to the last digit and never compare floating point numbers for equality. If you really need higher precision, you should use the arbitrary precision math functions instead. |
Strings can be specified using one of two sets of delimiters.
If the string is enclosed in double-quotes ("), variables within the string will be expanded (subject to some parsing limitations). As in C and Perl, the backslash ("\") character can be used in specifying special characters:
Table 6-1. Escaped characters
sequence | meaning |
---|---|
\n | linefeed (LF or 0x0A in ASCII) |
\r | carriage return (CR or 0x0D in ASCII) |
\t | horizontal tab (HT or 0x09 in ASCII) |
\\ | backslash |
\$ | dollar sign |
\" | double-quote |
\[0-7]{1,3} | the sequence of characters matching the regular expression is a character in octal notation |
\x[0-9A-Fa-f]{1,2} | the sequence of characters matching the regular expression is a character in hexadecimal notation |
You can escape any other character, but a warning will be issued at the highest warning level.
The second way to delimit a string uses the single-quote ("'") character. When a string is enclosed in single quotes, the only escapes that will be understood are "\\" and "\'". This is for convenience, so that you can have single-quotes and backslashes in a single-quoted string. Variables will not be expanded inside a single-quoted string.
Another way to delimit strings is by using here doc syntax ("<<<"). One should provide an identifier after <<<, then the string, and then the same identifier to close the quotation. The closing identifier must begin in the first column of the line.
Here doc text behaves just like a double-quoted string, without the double-quotes. This means that you do not need to escape quotes in your here docs, but you can still use the escape codes listed above. Variables are expanded, but the same care must be taken when expressing complex variables inside a here doc as with strings.
Example 6-1. Here doc string quoting example
|
Note: Here doc support was added in PHP 4.
Strings may be concatenated using the '.' (dot) operator. Note that the '+' (addition) operator will not work for this. Please see String operators for more information.
Characters within strings may be accessed by treating the string as a numerically-indexed array of characters, using C-like syntax. See below for examples.
Example 6-2. Some string examples
|
When a string is evaluated as a numeric value, the resulting value and type are determined as follows.
The string will evaluate as a double if it contains any of the characters '.', 'e', or 'E'. Otherwise, it will evaluate as an integer.
The value is given by the initial portion of the string. If the string starts with valid numeric data, this will be the value used. Otherwise, the value will be 0 (zero). Valid numeric data is an optional sign, followed by one or more digits (optionally containing a decimal point), followed by an optional exponent. The exponent is an 'e' or 'E' followed by one or more digits.
When the first expression is a string, the type of the variable will depend on the second expression.
$foo = 1 + "10.5"; // $foo is double (11.5) $foo = 1 + "-1.3e3"; // $foo is double (-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 = 1 + "10 Little Piggies"; // $foo is integer (11) $foo = "10.0 pigs " + 1; // $foo is integer (11) $foo = "10.0 pigs " + 1.0; // $foo is double (11) |
For more information on this conversion, see the Unix manual page for strtod(3).
If you would like to test any of the examples in this section, you can cut and paste the examples and insert the following line to see for yourself what's going on:
echo "\$foo==$foo; type is " . gettype ($foo) . "<br>\n"; |
Arrays actually act like both hash tables (associative arrays) and indexed arrays (vectors).
PHP supports both scalar and associative arrays. In fact, there is no difference between the two. You can create an array using the list() or array() functions, or you can explicitly set each array element value.
$a[0] = "abc"; $a[1] = "def"; $b["foo"] = 13; |
You can also create an array by simply adding values to the array. When you assign a value to an array variable using empty brackets, the value will be added onto the end of the array.
$a[] = "hello"; // $a[2] == "hello" $a[] = "world"; // $a[3] == "world" |
Arrays may be sorted using the asort(), arsort(), ksort(), rsort(), sort(), uasort(), usort(), and uksort() functions depending on the type of sort you want.
You can count the number of items in an array using the count() function.
You can traverse an array using next() and prev() functions. Another common way to traverse an array is to use the each() function.
Multi-dimensional arrays are actually pretty simple. For each dimension of the array, you add another [key] value to the end:
$a[1] = $f; # one dimensional examples $a["foo"] = $f; $a[1][0] = $f; # two dimensional $a["foo"][2] = $f; # (you can mix numeric and associative indices) $a[3]["bar"] = $f; # (you can mix numeric and associative indices) $a["foo"][4]["bar"][0] = $f; # four dimensional! |
In PHP3 it is not possible to reference multidimensional arrays directly within strings. For instance, the following will not have the desired result:
$a[3]['bar'] = 'Bob'; echo "This won't work: $a[3][bar]"; |
$a[3]['bar'] = 'Bob'; echo "This will work: " . $a[3][bar]; |
In PHP4, however, the whole problem may be circumvented by enclosing the array reference (inside the string) in curly braces:
$a[3]['bar'] = 'Bob'; echo "This will work: {$a[3][bar]}"; |
You can "fill up" multi-dimensional arrays in many ways, but the trickiest one to understand is how to use the array() command for associative arrays. These two snippets of code fill up the one-dimensional array in the same way:
# Example 1: $a["color"] = "red"; $a["taste"] = "sweet"; $a["shape"] = "round"; $a["name"] = "apple"; $a[3] = 4; # Example 2: $a = array( "color" => "red", "taste" => "sweet", "shape" => "round", "name" => "apple", 3 => 4 ); |
The array() function can be nested for multi-dimensional arrays:
<? $a = array( "apple" => array( "color" => "red", "taste" => "sweet", "shape" => "round" ), "orange" => array( "color" => "orange", "taste" => "tart", "shape" => "round" ), "banana" => array( "color" => "yellow", "taste" => "paste-y", "shape" => "banana-shaped" ) ); echo $a["apple"]["taste"]; # will output "sweet" ?> |
To initialize an object, you use the new statement to instantiate the object to a variable.
<?php class foo { function do_foo() { echo "Doing foo."; } } $bar = new foo; $bar->do_foo(); ?> |
For a full discussion, please read the section Classes and Objects.
PHP does not require (or support) explicit type definition in variable declaration; a variable's type is determined by the context in which that variable is used. That is to say, if you assign a string value to variable var, var becomes a string. If you then assign an integer value to var, it becomes an integer.
An example of PHP's automatic type conversion is the addition operator '+'. If any of the operands is a double, then all operands are evaluated as doubles, and the result will be a double. 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.
$foo = "0"; // $foo is string (ASCII 48) $foo++; // $foo is the string "1" (ASCII 49) $foo += 1; // $foo is now an integer (2) $foo = $foo + 1.3; // $foo is now a double (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.
If you wish to force a variable to be evaluated as a certain type, see the section on Type casting. If you wish to change the type of a variable, see settype().
If you would like to test any of the examples in this section, you can cut and paste the examples and insert the following line to see for yourself what's going on:
echo "\$foo==$foo; type is " . gettype ($foo) . "<br>\n"; |
Note: The behaviour of an automatic conversion to array is currently undefined.
$a = 1; // $a is an integer $a[0] = "f"; // $a becomes an array, with $a[0] holding "f"While the above example may seem like it should clearly result in $a becoming an array, the first element of which is 'f', consider this:
$a = "1"; // $a is a string $a[0] = "f"; // What about string offsets? What happens?Since PHP supports indexing into strings via offsets using the same syntax as array indexing, the example above leads to a problem: should $a become an array with its first element being "f", or should "f" become the first character of the string $a?
For this reason, as of PHP 3.0.12 and PHP 4.0b3-RC4, the result of this automatic conversion is considered to be undefined. Fixes are, however, being discussed.
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.
$foo = 10; // $foo is an integer $bar = (double) $foo; // $bar is a double |
The casts allowed are:
(int), (integer) - cast to integer
(real), (double), (float) - cast to double
(string) - cast to string
(array) - cast to array
(object) - cast to object
Note that tabs and spaces are allowed inside the parentheses, so the following are functionally equivalent:
$foo = (int) $bar; $foo = ( int ) $bar; |
It may not be obvious exactly what will happen when casting between certain types. For instance, the following should be noted.
When casting from a scalar or a string variable to an array, the variable will become the first element of the array:
$var = 'ciao'; $arr = (array) $var; echo $arr[0]; // outputs 'ciao' |
When casting from a scalar or a string variable to an object, the variable will become an attribute of the object; the attribute name will be 'scalar':
$var = 'ciao'; $obj = (object) $var; echo $obj->scalar; // outputs 'ciao' |
Variables in PHP are represented by a dollar sign followed by the name of the variable. The variable name is case-sensitive.
Variable names follow the same rules as other labels in PHP. A valid variable name starts with a letter or underscore, followed by any number of letters, numbers, or underscores. As a regular expression, it would be expressed thus: '[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*'
Note: For our purposes here, a letter is a-z, A-Z, and the ASCII characters from 127 through 255 (0x7f-0xff).
$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 ASCII 228. |
In PHP3, 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 Expressions.
PHP4 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. This also means that no copying is performed; thus, the assignment happens more quickly. However, any speedup will likely be noticed only in tight loops or when assigning large arrays or objects.
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 $foo; // $foo is altered too. echo $bar; ?> |
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. ?> |
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.
Despite these factors, here is a list of predefined variables available under a stock installation of PHP 3 running as a module under a stock installation of Apache 1.3.6.
For a list of all predefined variables (and lots of other useful information), please see (and use) phpinfo().
Note: This list is neither exhaustive nor intended to be. It is simply a guideline as to what sorts of predefined variables you can expect to have access to in your script.
These variables are created by the Apache webserver. If you are running another webserver, there is no guarantee that it will provide the same variables; it 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.
Note that few, if any, of these will be available (or indeed have any meaning) if running PHP on the command line.
What revision of the CGI specification the server is using; i.e. 'CGI/1.1'.
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 identification string, given in the headers when responding to requests.
Name and revision of the information protocol via which the page was requested; i.e. 'HTTP/1.0';
Which request method was used to access the page; i.e. 'GET', 'HEAD', 'POST', 'PUT'.
The query string, if any, via which the page was accessed.
The document root directory under which the current script is executing, as defined in the server's configuration file.
Contents of the Accept: header from the current request, if there is one.
Contents of the Accept-Charset: header from the current request, if there is one. Example: 'iso-8859-1,*,utf-8'.
Contents of the Accept-Encoding: header from the current request, if there is one. Example: 'gzip'.
Contents of the Accept-Language: header from the current request, if there is one. Example: 'en'.
Contents of the Connection: header from the current request, if there is one. Example: 'Keep-Alive'.
Contents of the Host: header from the current request, if there is one.
The address of the page (if any) which referred the browser to the current page. This is set by the user's browser; not all browsers will set this.
Contents of the User_Agent: header from the current request, if there is one. This is a string denoting the browser software being used to view the current page; i.e. 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 functionality to the capabilities of the user's browser.
The IP address from which the user is viewing the current page.
The port being used on the user's machine to communicate with the web server.
The absolute pathname of the currently executing script.
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.
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.
String containing the server version and virtual host name which are added to server-generated pages, if enabled.
Filesystem- (not document root-) based path to the current script, after the server has done any virtual-to-real mapping.
Contains the current script's path. This is useful for pages which need to point to themselves.
The URI which was given in order to access this page; for instance, '/index.html'.
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.
These variables are created by PHP itself.
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.
Contains the number of command line parameters passed to the script (if run on the command line).
The filename of the currently executing script, relative to the document root. If PHP is running as a command-line processor, this variable is not available.
An associative array of variables passed to the current script via HTTP cookies. Only available if variable tracking has been turned on via either the track_vars configuration directive or the <?php_track_vars?> directive.
An associative array of variables passed to the current script via the HTTP GET method. Only available if variable tracking has been turned on via either the track_vars configuration directive or the <?php_track_vars?> directive.
An associative array of variables passed to the current script via the HTTP POST method. Only available if variable tracking has been turned on via either the track_vars configuration directive or the <?php_track_vars?> directive.
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:
$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:
$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. An example:
$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:
$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.
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:
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:
Function Test () { static $a = 0; echo $a; $a++; } |
Now, every time the Test() function is called it will print the value of $a and increment it.
Static variables also provide one way to deal with recursive functions. A recursive function is one which calls itself. Care must be taken when writing a recursive function because it is possible to make it recurse indefinitely. You must make sure you have an adequate way of terminating the recursion. The following simple function recursively counts to 10, using the static variable $count to know when to stop:
Function Test () { static $count = 0; $count++; echo $count; if ($count < 10) { Test (); } $count--; } |
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:
$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.
$$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:
echo "$a ${$a}"; |
produces the exact same output as:
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.
When a form is submitted to a PHP script, any variables from that form will be automatically made available to the script by PHP. For instance, consider the following form:
Example 7-1. Simple form variable
|
When submitted, PHP will create the variable $name, which will will contain whatever what entered into the Name: field on the form.
PHP also understands arrays in the context of form variables, but only in one dimension. You may, for example, group related variables together, or use this feature to retrieve values from a multiple select input:
Example 7-2. More complex form variables
|
If PHP's track_vars feature is turned on, either by the track_vars configuration setting or the <?php_track_vars?> directive, then variables submitted via the POST or GET methods will also be found in the global associative arrays $HTTP_POST_VARS and $HTTP_GET_VARS as appropriate.
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.
PHP transparently supports HTTP cookies as defined by Netscape's Spec. Cookies are a mechanism for storing data in the remote browser and thus tracking or identifying return users. You can set cookies using the SetCookie() function. Cookies are part of the HTTP header, so the SetCookie function must be called before any output is sent to the browser. This is the same restriction as for the Header() function. Any cookies sent to you from the client will automatically be turned into a PHP variable just like GET and POST method data.
If you wish to assign multiple values to a single cookie, just add [] to the cookie name. For example:
SetCookie ("MyCookie[]", "Testing", time()+3600); |
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 7-3. SetCookie Example
|
PHP automatically makes environment variables available as normal PHP variables.
echo $HOME; /* Shows the HOME environment variable, if set. */ |
Since information coming in via GET, POST and Cookie mechanisms also automatically create PHP variables, it is sometimes best to explicitly read a variable from the environment in order to make sure that you are getting the right version. The getenv() function can be used for this. You can also set an environment variable with the putenv() function.
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:
$varname.ext; /* invalid variable name */ |
For this reason, it is important to note that PHP will automatically replace any dots in incoming variable names with underscores.
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. They are gettype(), is_long(), is_double(), is_string(), is_array(), and is_object().
PHP defines several constants and provides a mechanism for defining more at run-time. Constants are much like variables, save for the two facts that constants must be defined using the define() function, and that they cannot later be redefined to another value.
The predefined constants (always available) are:
The name of the script file presently being parsed. If used within a file which has been included or required, then the name of the included file is given, and not the name of the parent file.
The number of the line within the current script file which is being parsed. If used within a file which has been included or required, then the position within the included file is given.
The string representation of the version of the PHP parser presently in use; e.g. '3.0.8-dev'.
The name of the operating system on which the PHP parser is executing; e.g. 'Linux'.
A true value.
A false value.
Denotes an error other than a parsing error from which recovery is not possible.
Denotes a condition where PHP knows something is wrong, but will continue anyway; these can be caught by the script itself. An example would be an invalid regexp in ereg().
The parser choked on invalid syntax in the script file. Recovery is not possible.
Something happened which may or may not be an error. Execution continues. Examples include using an unquoted string as a hash index, or accessing a variable which has not been set.
All of the E_* constants rolled into one. If used with error_reporting(), will cause any and all problems noticed by PHP to be reported.
The E_* constants are typically used with the error_reporting() function for setting the error reporting level. See all these constants at Error handling.
You can define additional constants using the define() function.
Note that these are constants, not C-style macros; only valid scalar data may be represented by a constant.
Example 8-1. Defining Constants
|
Example 8-2. Using __FILE__ and __LINE__
|
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:
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 three scalar value types: integer values, floating point values and string 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.
So far, users of PHP/FI 2 shouldn't feel any change. However, 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/FI 2 and many other languages may be familiar with the notation of variable++ and variable--. These are increment and decrement operators. In PHP/FI 2, the statement '$a++' has no value (is not an expression), and thus you can't assign it or use it in any way. PHP enhances the increment/decrement capabilities by making these expressions as well, like in C. In PHP, like in C, there are two types of increment - pre-increment and post-increment. Both pre-increment and post-increment essentially increment the variable, and the effect on the variable is idential. 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 0 or 1, meaning FALSE or TRUE (respectively). PHP supports > (bigger than), >= (bigger than or equal to), == (equal), != (not equal), < (smaller than) and <= (smaller than or equal to). 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:
$first ? $second : $third |
The following example should help you understand pre- and post-increment and expressions in general a bit better:
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. */ |
In the beginning of the chapter we said that we'll be describing the various statement types, and as promised, expressions can be statements. However, not every expression is a statement. 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 (PHP doesn't have a dedicated boolean type). The truth value of expressions in PHP is calculated in a similar way to perl. Any numeric non-zero numeric value is TRUE, zero is FALSE. Be sure to note that negative values are non-zero and are thus considered TRUE! The empty string and the string "0" are FALSE; all other strings are TRUE. With non-scalar values (arrays and objects) - if the value contains no elements it's considered FALSE, otherwise it's considered TRUE.
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.
Remember basic arithmetic from school? These work just like those.
Table 10-1. Arithmetic Operators
Example | Name | Result |
---|---|---|
$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 an integer value (the result of an integer division) if the two operands are integers (or strings that get converted to integers). If either operand is a floating-point value, floating-point division is performed.
The basic assignment operator is "=". Your first inclination might be to think of this as "equal to". Don't. It really means that the the left operand gets set to the value of the expression on the rights (that is, "gets set to").
The value of an assignment expression is the value assigned. That is, the value of "$a = 3" is 3. This allows you to do some tricky things:
$a = ($b = 4) + 5; // $a is equal to 9 now, and $b has been set to 4. |
In addition to the basic assignment operator, there are "combined operators" for all of the binary arithmetic 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:
$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. PHP4 supports assignment by reference, using the $var = &$othervar; syntax, but this is not possible in PHP3. 'Assignment by reference' means that both variables end up pointing at the same data, and nothing is copied anywhere.
Bitwise operators allow you to turn specific bits within an integer on or off.
Table 10-2. Bitwise Operators
Example | Name | Result |
---|---|---|
$a & $b | And | Bits that are set in both $a and $b are set. |
$a | $b | Or | Bits that are set in either $a or $b are set. |
$a ^ $b | Xor | Bits that are set in $a or $b but not both are set. |
~ $a | Not | Bits that are set in $a are not set, and vice versa. |
$a << $b | Shift left | Shift the bits of $a $b steps to the left (each step means "multiply by two") |
$a >> $b | Shift right | Shift the bits of $a $b steps to the right (each step means "divide by two") |
Comparison operators, as their name implies, allow you to compare two values.
Table 10-3. Comparison Operators
Example | Name | Result |
---|---|---|
$a == $b | Equal | True if $a is equal to $b. |
$a === $b | Identical | True if $a is equal to $b, and they are of the same type. (PHP4 only) |
$a != $b | Not equal | True if $a is not equal to $b. |
$a !== $b | Not identical | True if $a is not equal to $b, or they are not of the same type. (PHP4 only) |
$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. |
Another conditional operator is the "?:" (or trinary) operator, which operates as in C and many other languages.
(expr1) ? (expr2) : (expr3); |
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 global variable $php_errormsg. This variable will be overwritten on each error, so check early if you want to use it.
<?php /* Intentional SQL error (extra quote): */ $res = @mysql_query ("select name, code from 'namelist") or die ("Query failed: error was '$php_errormsg'"); ?> |
See also error_reporting().
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. |
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).
$output = `ls -al`; echo "<pre>$output</pre>"; |
See also system(), passthru(), exec(), popen(), and escapeshellcmd().
PHP supports C-style pre- and post-increment and decrement operators.
Table 10-4. 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"; ?> |
Table 10-5. 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 | Or | 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.)
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.
The following table lists the precedence of operators with the lowest-precedence operators listed first.
Table 10-6. Operator Precedence
Associativity | Operators |
---|---|
left | , |
left | or |
left | xor |
left | and |
right | |
left | = += -= *= /= .= %= &= |= ^= ~= <<= >>= |
left | ? : |
left | || |
left | && |
left | | |
left | ^ |
left | & |
non-associative | == != === !== |
non-associative | < <= > >= |
left | << >> |
left | + - . |
left | * / % |
right | ! ~ ++ -- (int) (double) (string) (array) (object) @ |
right | [ |
non-associative | new |
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.
$a = "Hello "; $b = $a . "World!"; // now $b contains "Hello World!" $a = "Hello "; $a .= "World!"; // now $a contains "Hello World!" |
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 of 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.
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, expr is evaluated to its truth value. If expr evaluates to TRUE, PHP will execute statement, and if it evaluates to FALSE - it'll ignore it.
The following example would display a is bigger than b if $a is bigger than $b:
if ($a > $b) print "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:
if ($a > $b) { print "a is bigger than b"; $b = $a; } |
If statements can be nested indefinitely within other if statements, which provides you with complete flexibility for conditional execution of the various parts of your program.
Often you'd want to execute a statement if a certain condition is met, and a different statement if the condition is not met. This is what else is for. else extends an if statement to execute a statement in case the expression in the if statement evaluates to FALSE. For example, the following code would display a is bigger than b if $a is bigger than $b, and a is NOT bigger than b otherwise:
if ($a > $b) { print "a is bigger than b"; } else { print "a is NOT bigger than b"; } |
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:
if ($a > $b) { print "a is bigger than b"; } elseif ($a == $b) { print "a is equal to b"; } else { print "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.
PHP offers an alternative syntax for some of its control structures; namely, if, while, for, 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;, or endswitch;, respectively.
<?php if ($a == 5): ?> A is equal to 5 <?php endif; ?> |
In the above example, the HTML block "A = 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:
if ($a == 5): print "a equals 5"; print "..."; elseif ($a == 6): print "a equals 6"; print "!!!"; else: print "a is neither 5 nor 6"; endif; |
while loops are the simplest type of loop in PHP. They behave just like their C counterparts. The basic form of a while statement is:
while (expr) statement |
The meaning of a while statement is simple. It tells PHP to execute the nested statement(s) repeatedly, as long as the while expression evaluates to TRUE. The value of the expression is checked each time at the beginning of the loop, so even if this value changes during the execution of the nested statement(s), execution will not stop until the end of the iteration (each time PHP runs the statements in the loop is one iteration). Sometimes, if the while expression evaluates to FALSE from the very beginning, the nested statement(s) won't even be run once.
Like with the if statement, you can group multiple statements within the same while loop by surrounding a group of statements with curly braces, or by using the alternate syntax:
while (expr): statement ... endwhile; |
The following examples are identical, and both print numbers from 1 to 10:
/* example 1 */ $i = 1; while ($i <= 10) { print $i++; /* the printed value would be $i before the increment (post-increment) */ } /* example 2 */ $i = 1; while ($i <= 10): print $i; $i++; endwhile; |
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 guarenteed to run (the truth expression is only checked at the end of the iteration), whereas it's may not necessarily run with a regular while loop (the truth expression is checked at the beginning of each iteration, if it evaluates to FALSE right from the beginning, the loop execution would end immediately).
There is just one syntax for do..while loops:
$i = 0; do { print $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:
do { if ($i < 5) { print "i is not big enough"; break; } $i *= $factor; if ($i < $minimum_limit) { break; } print "i is ok"; ...process i... } while(0); |
Don't worry if you don't understand this right away or at all. You can code scripts and even powerful scripts without using this `feature'.
for 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. expr2 being empty means the loop should be run indefinitely (PHP implicitly considers it as TRUE, like C). This may not be as useless as you might think, since often you'd want to end the loop using a conditional break statement instead of using the for truth expression.
Consider the following examples. All of them display numbers from 1 to 10:
/* example 1 */ for ($i = 1; $i <= 10; $i++) { print $i; } /* example 2 */ for ($i = 1;;$i++) { if ($i > 10) { break; } print $i; } /* example 3 */ $i = 1; for (;;) { if ($i > 10) { break; } print $i; $i++; } /* example 4 */ for ($i = 1; $i <= 10; 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; |
Other languages have a foreach statement to traverse an array or hash. PHP3 has no such construct; PHP4 does (see foreach). In PHP3, you can combine while with the list() and each() functions to achieve the same effect. See the documentation for these functions for an example.
PHP4 (not PHP3) includes a foreach construct, much like perl and some other languages. This simply gives an easy way to iterate over arrays. There are two syntaxes; the second is a minor but useful extension of the first:
foreach(array_expression as $value) statement foreach(array_expression as $key => $value) statement |
The first form loops over the array given by array_expression. On each loop, the value of the current element is assigned to $value and the internal array pointer is advanced by one (so on the next loop, you'll be looking at the next element).
The second form does the same thing, except that the current element's key will be assigned to the variable $key on each loop.
Note: When foreach first starts executing, the internal array pointer is automatically reset to the first element of the array. This means that you do not need to call reset() before a foreach loop.
Note: Also note that foreach operates on a copy of the specified array, not the array itself, therefore the array pointer is not modified like with the each construct.
You may have noticed that the following are functionally identical:
reset ($arr); while (list(, $value) = each ($arr)) { echo "Value: $value<br>\n"; } foreach ($arr as $value) { echo "Value: $value<br>\n"; } |
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:
/* foreach example 1: value only */ $a = array (1, 2, 3, 17); foreach ($a as $v) { print "Current value of \$a: $v.\n"; } /* foreach example 2: value (with key printed for illustration) */ $a = array (1, 2, 3, 17); $i = 0; /* for illustrative purposes only */ foreach($a as $v) { print "\$a[$i] => $k.\n"; } /* foreach example 3: key and value */ $a = array ( "one" => 1, "two" => 2, "three" => 3, "seventeen" => 17 ); foreach($a as $k => $v) { print "\$a[$k] => $v.\n"; } |
break ends execution of the current for, while, or switch structure.
break accepts an optional numeric argument which tells it how many nested enclosing structures are to be broken out of.
$arr = array ('one', 'two', 'three', 'four', 'stop', 'five'); while (list (, $val) = each ($arr)) { if ($val == 'stop') { break; /* You could also write 'break 1;' here. */ } echo "$val<br>\n"; } /* Using the optional argument. */ $i = 0; while (++$i) { switch ($i) { case 5: echo "At 5<br>\n"; break 1; /* Exit only the switch. */ case 10: echo "At 10; quitting<br>\n"; break 2; /* Exit the switch and the while. */ default: break; } } |
continue is used within looping structures to skip the rest of the current loop iteration and continue execution at the beginning of the next iteration.
continue accepts an optional numeric argument which tells it how many levels of enclosing loops it should skip to the end of.
while (list ($key, $value) = each ($arr)) { if (!($key % 2)) { // skip odd members continue; } do_something_odd ($value); } $i = 0; while ($i++ < 5) { echo "Outer<br>\n"; while (1) { echo " Middle<br>\n"; while (1) { echo " Inner<br>\n"; continue 3; } echo "This never gets output.<br>\n"; } echo "Neither does this.<br>\n"; } |
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.
The following two examples are two different ways to write the same thing, one using a series of if statements, and the other using the switch statement:
if ($i == 0) { print "i equals 0"; } if ($i == 1) { print "i equals 1"; } if ($i == 2) { print "i equals 2"; } switch ($i) { case 0: print "i equals 0"; break; case 1: print "i equals 1"; break; case 2: print "i equals 2"; 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:
switch ($i) { case 0: print "i equals 0"; case 1: print "i equals 1"; case 2: print "i equals 2"; } |
Here, if $i equals to 0, PHP would execute all of the print statements! If $i equals to 1, PHP would execute the last two print statements, and only if $i equals to 2, you'd get the 'expected' behavior and only 'i equals 2' would be displayed. So, it's 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.
switch ($i) { case 0: case 1: case 2: print "i is less than 3 but not negative"; break; case 3: print "i is 3"; } |
A special case is the default case. This case matches anything that wasn't matched by the other cases. For example:
switch ($i) { case 0: print "i equals 0"; break; case 1: print "i equals 1"; break; case 2: print "i equals 2"; break; default: print "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 .
switch ($i): case 0: print "i equals 0"; break; case 1: print "i equals 1"; break; case 2: print "i equals 2"; break; default: print "i is not equal to 0, 1 or 2"; endswitch; |
The require() statement replaces itself with the specified file, much like the C preprocessor's #include works.
If "URL fopen wrappers" are enabled in PHP (which they are in the default configuration), you can specify the file to be require()ed using an URL instead of a local pathname. See Remote files and fopen() for more information.
An important note about how this works is that when a file is include()ed or require()ed, parsing drops out of PHP mode and into HTML mode at the beginning of the target file, and resumes PHP mode 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.
require() is not actually a function in PHP; rather, it is a language construct. It is subject to some different rules than functions are. For instance, require() is not subject to any containing control structures. For another, it does not return any value; attempting to read a return value from a require() call results in a parse error.
Unlike include(), require() will always read in the target file, even if the line it's on never executes. If you want to conditionally include a file, use include(). The conditional statement won't affect the require(). However, if the line on which the require() occurs is not executed, neither will any of the code in the target file be executed.
Similarly, looping structures do not affect the behaviour of require(). Although the code contained in the target file is still subject to the loop, the require() itself happens only once.
This means that you can't put a require() statement inside of a loop structure and expect it to include the contents of a different file on each iteration. To do that, use an include() statement.
require ('header.inc'); |
When a file is require()ed, the code it contains inherits the variable scope of the line on which the require() occurs. Any variables available at that line in the calling file will be available within the called file. If the require() 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.
If the require()ed file is called via HTTP using the fopen wrappers, and if the target server interprets the target file as PHP code, variables may be passed to the require()ed file using an URL request string as used with HTTP GET. This is not strictly speaking the same thing as require()ing 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.
/* This example assumes that someserver is configured to parse .php * files and not .txt files. Also, 'works' here means that the variables * $varone and $vartwo are available within the require()ed file. */ /* Won't work; file.txt wasn't handled by someserver. */ require ("http://someserver/file.txt?varone=1&vartwo=2"); /* Won't work; looks for a file named 'file.php?varone=1&vartwo=2' * on the local filesystem. */ require ("file.php?varone=1&vartwo=2"); /* Works. */ require ("http://someserver/file.php?varone=1&vartwo=2"); $varone = 1; $vartwo = 2; require ("file.txt"); /* Works. */ require ("file.php"); /* Works. */ |
In PHP3, it is possible to execute a return statement inside a require()ed file, as long as that statement occurs in the global scope of the require()ed file. It may not occur within any block (meaning inside braces ({}). In PHP4, however, this ability has been discontinued. If you need this functionality, see include().
See also include(), require_once(), include_once(), readfile(), and virtual().
The include() statement includes and evaluates the specified file.
If "URL fopen wrappers" are enabled in PHP (which they are in the default configuration), you can specify the file to be include()ed using an URL instead of a local pathname. See Remote files and fopen() for more information.
An important note about how this works is that when a file is include()ed or require()ed, 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.
This happens each time the include() statement is encountered, so you can use an include() statement within a looping structure to include a number of different files.
$files = array ('first.inc', 'second.inc', 'third.inc'); for ($i = 0; $i < count($files); $i++) { include $files[$i]; } |
include() differs from require() in that the include statement is re-evaluated each time it is encountered (and only when it is being executed), whereas the require() statement is replaced by the required file when it is first encountered, whether the contents of the file will be evaluated or not (for example, if it is inside an if statement whose condition evaluated to false).
Because include() is a special language construct, you must enclose it within a statement block if it is inside a conditional block.
/* This is WRONG and will not work as desired. */ if ($condition) include($file); else include($other); /* This is CORRECT. */ if ($condition) { include($file); } else { include($other); } |
In both PHP3 and PHP4, it is possible to execute a return statement inside an include()ed file, in order to terminate processing in that file and return to the script which called it. Some differences in the way this works exist, however. The first is that in PHP3, the return may not appear inside a block unless it's a function block, in which case the return applies to that function and not the whole file. In PHP4, however, this restriction does not exist. Also, PHP4 allows you to return values from include()ed files. You can take the value of the include() call as you would a normal function. This generates a parse error in PHP3.
Example 11-1. include() in PHP3 and PHP4 Assume the existence of the following file (named test.inc) in the same directory as the main file:
Assume that the main file (main.html) contains the following:
When main.html is called in PHP3, it will generate a parse error on line 2; you can't take the value of an include() in PHP3. In PHP4, however, the result will be:
Now, assume that main.html has been altered to contain the following:
In PHP4, the output will be:
The above parse error is a result of the fact that the return statement is enclosed in a non-function block within test.inc. When the return is moved outside of the block, the output is:
The spurious '27' is due to the fact that PHP3 does not support returning values from files like that. |
When a file is include()ed, 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. 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.
If the include()ed file is called via HTTP using the fopen wrappers, and if the target server interprets the target file as PHP code, variables may be passed to the include()ed file using an URL request string as used with HTTP GET. This is not strictly speaking the same thing as include()ing 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.
/* This example assumes that someserver is configured to parse .php * files and not .txt files. Also, 'works' here means that the variables * $varone and $vartwo are available within the include()ed file. */ /* Won't work; file.txt wasn't handled by someserver. */ include ("http://someserver/file.txt?varone=1&vartwo=2"); /* Won't work; looks for a file named 'file.php?varone=1&vartwo=2' * on the local filesystem. */ include ("file.php?varone=1&vartwo=2"); /* Works. */ include ("http://someserver/file.php?varone=1&vartwo=2"); $varone = 1; $vartwo = 2; include ("file.txt"); /* Works. */ include ("file.php"); /* Works. */ |
See also require(), require_once(), include_once(), readfile(), and virtual().
The require_once() statement replaces itself with the specified file, much like the C preprocessor's #include works, and in that respect is similar to the require() statement. The main difference is that in an inclusion chain, the use of require_once() will assure that the code is added to your script only once, and avoid clashes with variable values or function names that can happen.
For example, if you create the following 2 include files utils.inc and foolib.inc
Example 11-2. utils.inc
|
Example 11-3. foolib.inc
|
Example 11-4. cause_error_require.php
|
GLOBALS ARE NICE GLOBALS ARE NICE Fatal error: Cannot redeclare causeerror() in utils.inc on line 5 |
Example 11-5. foolib.inc (fixed)
|
Example 11-6. avoid_error_require_once.php
|
GLOBALS ARE NICE this is requiring globals.inc again which is also required in foolib.inc Running goodTea: Oolong tea tastes good! Printing foo: Array ( [0] => 1 [1] => Array ( [0] => complex [1] => quaternion ) ) |
Also note that, analogous to the behavior of the #include of the C preprocessor, this statement acts at "compile time", e.g. when the script is parsed and before it is executed, and should not be used for parts of the script that need to be inserted dynamically during its execution. You should use include_once() or include() for that purpose.
For more examples on using require_once() and include_once(), look at the PEAR code included in the latest PHP source code distributions.
See also: require(), include(), include_once(), get_required_files(), get_included_files(), readfile(), and virtual().
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 important difference that if the code from a file has already been included, it will not be included again.
As mentioned in the require_once() description, the include_once() should be used in the cases in which the same file might be included and evaluated more than once during a particular execution of a script, and you want to be sure that it is included exactly once to avoid problems with function redefinitions, variable value reassignments, etc.
For more examples on using require_once() and include_once(), look at the PEAR code included in the latest PHP source code distributions.
See also: require(), include(), require_once(), get_required_files(), get_included_files(), readfile(), and virtual().
A function may be defined using syntax such as the following:
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.
In PHP3, functions must be defined before they are referenced. No such requirement exists in PHP4.
PHP does not support function overloading, nor is it possible to undefine or redefine previously-declared functions.
PHP3 does not support variable numbers of arguments to functions, although default arguments are supported (see Default argument values for more information). PHP4 supports both: see Variable-length argument lists and the function references for func_num_args(), func_get_arg(), and func_get_args() for more information.
Information may be passed to functions via the argument list, which is a comma-delimited list of variables and/or constants.
PHP supports passing arguments by value (the default), passing by reference, and default argument values. Variable-length argument lists are supported only in PHP4 and later; see Variable-length argument lists and the function references for func_num_args(), func_get_arg(), and func_get_args() for more information. A similar effect can be achieved in PHP3 by passing an array of arguments to a function:
function takes_array($input) { echo "$input[0] + $input[1] = ", $input[0]+$input[1]; } |
By default, function arguments are passed by value (so that if you change the value of the argument within the function, it does not get changed outside of the function). If you wish to allow a function to modify its arguments, you must pass them by reference.
If you want an argument to a function to always be passed by reference, you can prepend an ampersand (&) to the argument name in the function definition:
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.' |
If you wish to pass a variable by reference to a function which does not do this by default, you may prepend an ampersand to the argument name in the function call:
function foo ($bar) { $bar .= ' and something extra.'; } $str = 'This is a string, '; foo ($str); echo $str; // outputs 'This is a string, ' foo (&$str); echo $str; // outputs 'This is a string, and something extra.' |
A function may define C++-style default values for scalar arguments as follows:
function makecoffee ($type = "cappucino") { return "Making a cup of $type.\n"; } echo makecoffee (); echo makecoffee ("espresso"); |
The output from the above snippet is:
Making a cup of cappucino. Making a cup of espresso. |
The default value must be a constant expression, not (for example) a variable or class member.
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:
function makeyogurt ($type = "acidophilus", $flavour) { return "Making a bowl of $type $flavour.\n"; } echo makeyogurt ("raspberry"); // won't work as expected |
The output of the above example is:
Warning: Missing argument 2 in call to makeyogurt() in /usr/local/etc/httpd/htdocs/php3test/functest.html on line 41 Making a bowl of raspberry . |
Now, compare the above with this:
function makeyogurt ($flavour, $type = "acidophilus") { return "Making a bowl of $type $flavour.\n"; } echo makeyogurt ("raspberry"); // works as expected |
The output of this example is:
Making a bowl of acidophilus raspberry. |
PHP4 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.
Values are returned by using the optional return statement. Any type may be returned, including lists and objects.
function square ($num) { return $num * $num; } echo square (4); // outputs '16'. |
You can't return multiple values from a function, but similar results can be obtained by returning a list.
function small_numbers() { return array (0, 1, 2); } list ($zero, $one, $two) = small_numbers(); |
To return a reference from a function, you have to use the reference operator & in both the function declaration and when assigning the return value to a variable:
function &returns_reference() { return &$someref; } $newref = &returns_reference(); |
The old_function statement allows you to declare a function using a syntax identical to PHP/FI2 (except you must replace 'function' with 'old_function'.
This is a deprecated feature, and should only be used by the PHP/FI2->PHP3 convertor.
Warning |
Functions declared as old_function cannot be called from PHP's internal code. Among other things, this means you can't use them in functions such as usort(), array_walk(), and register_shutdown_function(). You can get around this limitation by writing a wrapper function (in normal PHP3 form) to call the old_function. |
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.
Example 12-1. Variable function example
|
A class is a collection of variables and functions working with these variables. A class is defined using the following syntax:
<?php class Cart { var $items; // Items in our shopping cart // Add $num articles of $artnr to the cart function add_item ($artnr, $num) { $this->items[$artnr] += $num; } // Take $num articles of $artnr out of the cart function remove_item ($artnr, $num) { if ($this->items[$artnr] > $num) { $this->items[$artnr] -= $num; return true; } else { return false; } } } ?> |
This defines a class named Cart that consists of an associative array of articles in the cart and two functions to add and remove items from this cart.
Classes are types, that is, they are blueprints for actual variables. You have to create a variable of the desired type with the new operator.
$cart = new Cart; $cart->add_item("10", 1); |
This creates an object $cart of the class Cart. The function add_item() of that object is being called to add 1 item of article number 10 to the cart.
Classes can be extensions of other classes. The extended or derived class has all variables and functions of the base class and what you add in the extended definition. This is done using the extends keyword. Multiple inheritance is not supported.
class Named_Cart extends Cart { var $owner; function set_owner ($name) { $this->owner = $name; } } |
This defines a class Named_Cart that has all variables and functions of Cart plus an additional variable $owner and an additional function set_owner(). You create a named cart the usual way and can now set and get the carts owner. You can still use normal cart functions on named carts:
$ncart = new Named_Cart; // Create a named cart $ncart->set_owner ("kris"); // Name that cart print $ncart->owner; // print the cart owners name $ncart->add_item ("10", 1); // (inherited functionality from cart) |
Within functions of a class the variable $this means this object. You have to use $this->something to access any variable or function named something within your current object.
Constructors are functions in a class that are automatically called when you create a new instance of a class. A function becomes a constructor when it has the same name as the class.
class Auto_Cart extends Cart { function Auto_Cart () { $this->add_item ("10", 1); } } |
This defines a class Auto_Cart that is a Cart plus a constructor which initializes the cart with one item of article number "10" each time a new Auto_Cart is being made with "new". Constructors can also take arguments and these arguments can be optional, which makes them much more useful.
class Constructor_Cart extends Cart { function Constructor_Cart ($item = "10", $num = 1) { $this->add_item ($item, $num); } } // Shop the same old boring stuff. $default_cart = new Constructor_Cart; // Shop for real... $different_cart = new Constructor_Cart ("20", 17); |
Caution |
For derived classes, the constructor of the parent class is not automatically called when the derived class's constructor is called. |
References in PHP are means to call same variable content with different names. They are not like C pointers, they are symbol table aliases. Note that in PHP, variable names and variable content are different, so same content can have different names. The most close analogy is Unix filenames and files - variable names are directory entries, while variable contents is the file itself. References can be thought of as hardlinking in Unix filesystem.
PHP references allow you to make two variables to refer to the same content. Meaning, when you do:
$a =& $b |
Note: $a and $b are completely equal here, that's not $a is pointing to $b or vice versa, that's $a and $b pointing to the same place.
The second thing references do is to pass variables by-reference. This is done by making local function variable and caller variable to be reference to the same content. Example:
function foo (&$var) { $var++; } $a=5; foo ($a); |
The third thing reference can do is return by-reference.
As said above, references aren't pointers. That means, the following construct won't do what you expect:
function foo (&$var) { $var =& $GLOBALS["baz"]; } foo($bar); |
What will happen that $var in foo will be bound with $bar in caller, but then it will be re-bound with $GLOBALS["baz"]. There's no way to bind $bar in the caller to something else using 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).
Returning by-refernce it is useful when you want to use function to find variable which should be bound to. When returning references, use this syntax:
function &find_var ($param) { ...code... return $found_var; } $foo =& find_var ($bar); $foo->x = 2; |
Note: Unlike parameter passing, here you have to use & in both places - to indicate that you return by-reference, not a copy as usual, and to indicate than reference binding and not usual assignment should be done for $foo.
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:
$a = 1; $b =& $a; unset ($a); |
Again, it might be useful to think about this as analogous to Unix unlink call.
Many syntax constructs in PHP are implemented via referencing mechanisms, so everything told above about reference binding also apply to these constructs. Some constructs, like passing and returning by-reference, are mentioned above. Other constructs that use references are:
When you declare variable as global $var you are in fact creating reference to a global variable. That means, this is the same as:
$var =& $GLOBALS["var"]; |
That means, for example, that unsetting $var won't unset global variable.
There are several types of errors and warnings in PHP. They are:
Table 15-1. PHP error types
Value | Constant | Description | Note |
---|---|---|---|
1 | E_ERROR | fatal run-time errors | |
2 | E_WARNING | run-time warnings (non fatal errors) | |
4 | E_PARSE | compile-time parse errors | |
8 | E_NOTICE | run-time notices (less serious than warnings) | |
16 | E_CORE_ERROR | fatal errors that occur during PHP's initial startup | PHP 4 only |
32 | E_CORE_WARNING | warnings (non fatal errors) that occur during PHP's initial startup | PHP 4 only |
64 | E_COMPILE_ERROR | fatal compile-time errors | PHP 4 only |
128 | E_COMPILE_WARNING | compile-time warnings (non fatal errors) | PHP 4 only |
256 | E_USER_ERROR | user-generated error message | PHP 4 only |
512 | E_USER_WARNING | user-generated warning message | PHP 4 only |
1024 | E_USER_NOTICE | user-generated notice message | PHP 4 only |
E_ALL | all of the above, as supported |
The above values (either numerical or symbolic) are used to build up a bitmask that specifies which errors to report. You can use the bitwise operators to combine these values or mask out certain types of errors. Note that only '|', '~', '!', and '&' will be understood within php.ini, however, and that no bitwise operators will be understood within php3.ini.
In PHP 4, the default error_reporting setting is E_ALL & ~E_NOTICE, meaning to display all errors and warnings which are not E_NOTICE-level. In PHP 3, the default setting is (E_ERROR | E_WARNING | E_PARSE), meaning the same thing. Note, however, that since constants are not supported in PHP 3's php3.ini, the error_reporting setting there must be numeric; hence, it is 7.
The initial setting can be changed in the ini file with the error_reporting directive, in your Apache httpd.conf file with the php_error_reporting (php3_error_reporting for PHP 3) directive, and lastly it may be set at runtime within a script by using the error_reporting() function.
Warning |
When upgrading code or servers from PHP 3 to PHP 4 you should check these settings and calls to error_reporting() or you might disable reporting the new error types, especially E_COMPILE_ERROR. This may lead to empty documents without any feedback of what happened or where to look for the problem. |
All PHP expressions can also be called with the "@" prefix, which turns off error reporting for that particular expression. If an error occurred during such an expression and the track_errors feature is enabled, you can find the error message in the global variable $php_errormsg.
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. |
PHP is not limited to creating just HTML output. It can also be used to create and manipulate image files in a variety of different image formats, including gif, png, jpg, wbmp, and xpm. Even more convenient, php can output image streams directly to a browser. You will need to compile PHP with the GD library of image functions for this to work. GD and PHP may also require other libraries, depending on which image formats you want to work with.
Example 16-1. GIF creation with PHP
|
The HTTP Authentication hooks in PHP are only available when it is running as an Apache module and is hence not available in the CGI version. In an Apache module PHP script, it is possible to use the Header() function to send an "Authentication Required" message to the client browser causing it to pop up a Username/Password input window. Once the user has filled in a username and a password, the URL containing the PHP script will be called again with the variables, $PHP_AUTH_USER, $PHP_AUTH_PW and $PHP_AUTH_TYPE set to the user name, password and authentication type respectively. Only "Basic" authentication is supported at this point. See the Header() function for more information.
An example script fragment which would force client authentication on a page would be the following:
Example 17-1. HTTP Authentication example
|
Instead of simply printing out the $PHP_AUTH_USER and $PHP_AUTH_PW, you would probably want to check the username and password for validity. Perhaps by sending a query to a database, or by looking up the user in a dbm file.
Watch out for buggy Internet Explorer browsers out there. They seem very picky about the order of the headers. Sending the WWW-Authenticate header before the HTTP/1.0 401 header seems to do the trick for now.
In order to prevent someone from writing a script which reveals the password for a page that was authenticated through a traditional external mechanism, the PHP_AUTH variables will not be set if external authentication is enabled for that particular page. In this case, the $REMOTE_USER variable can be used to identify the externally-authenticated user.
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 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 17-2. HTTP Authentication example forcing a new name/password
|
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).
Also note that this does not work using Microsoft's IIS server and the CGI version of PHP due to a limitation of IIS.
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() 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.
Any cookies sent to you from the client will automatically be turned into a PHP variable just like GET and POST method data. If you wish to assign multiple values to a single cookie, just add [] to the cookie name. For more details see the setcookie() function.
PHP is capable of receiving file uploads from any RFC-1867 compliant browser (which includes Netscape Navigator 3 or later, Microsoft Internet Explorer 3 with a patch from Microsoft, or later without a patch). 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.
Note that 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.
A file upload screen can be built by creating a special form which looks something like this:
Example 19-1. File Upload Form
|
$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".
Files will by default be stored in the server's default temporary directory. This 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.
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 $file_size variable to throw away any files that are either too small or too big. You could use the $file_type variable to throw away any files that didn't match a certain type criteria. Whatever the logic, you should either delete the file from the temporary directory or move it elsewhere.
The file will be deleted from the temporary directory at the end of the request if it has not been moved away or renamed.
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 PHP3.ini file or the corresponding php3_upload_max_filesize Apache .conf directive. The default is 2 Megabytes.
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.
It is possible to upload multiple files simultaneously and have the information organized automatically in arrays for you. To do so, you need to use the same array submission syntax in the HTML form as you do with multiple selects and checkboxes:
Note: Support for multiple file uploads was added in version 3.0.10.
Example 19-2. Uploading multiple files
|
When the above form is submitted, the arrays $userfile, $userfile_name, and $userfile_size will be formed in the global scope (as well as in $HTTP_POST_FILES ($HTTP_POST_VARS in PHP 3)). 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, $userfile_name[0] would contain the value review.html, and $userfile_name[1] would contain the value xwp.out. Similarly, $userfile_size[0] would contain review.html's filesize, and so forth.
$userfile['name'][0], $userfile['tmp_name'][0], $userfile['size'][0], and $userfile['type'][0] are also set.
PHP provides support for the HTTP PUT method used by clients such as Netscape Composer and W3C Amaya. PUT requests are much simpler than a file upload 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.php3 |
This tells Apache to send all PUT requests for URIs that match the context in which you put this line to the put.php3 script. This assumes, of course, that you have PHP enabled for the .php3 extension and PHP is active.
Inside your put.php3 file you would then do something like this:
<? copy($PHP_UPLOADED_FILE_NAME,$DOCUMENT_ROOT.$REQUEST_URI); ?> |
This would copy the file to the location requested by the remote client. You would probably want to perform some checks and/or authenticate the user before performing this file copy. The only trick here is that when PHP sees a PUT-method request it stores the uploaded file in a temporary file just like those handled but the POST-method. When the request ends, this temporary file is deleted. So, your PUT handling PHP script has to copy that file somewhere. The filename of this temporary file is in the $PHP_PUT_FILENAME variable, and you can see the suggested destination filename in the $REQUEST_URI (may vary on non-Apache web servers). This destination filename is the one that the remote client specified. You do not have to listen to this client. You could, for example, copy all uploaded files to a special uploads directory.
As long as support for the "URL fopen wrapper" is enabled when you configure PHP (which it is unless you explicitly pass the --disable-url-fopen-wrapper flag to configure), you can use HTTP and FTP URLs with most functions that take a filename as a parameter, including the require() and include() statements.
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 20-1. Getting the title of a remote page
|
You can also write to files on an FTP as long you connect as a user with the correct access rights, and the file doesn't exist already. 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 20-2. Storing data on a remote server
|
Note: You might get the idea from the example above to use this technique to write to a remote log, but as mentioned above, you can only write to a new file using the URL fopen() wrappers. To do distributed logging like that, you should take a look at syslog().
Note: The following applies to 3.0.7 and later.
Internally in PHP a connection status is maintained. There are 3 possible states:
0 - NORMAL
1 - ABORTED
2 - TIMEOUT
When a PHP script is running normally the NORMAL state, is active. If the remote client disconnects the ABORTED state flag is turned on. A remote client disconnect is usually caused by the user hitting his STOP button. If the PHP-imposed time limit (see set_time_limit()) is hit, the TIMEOUT state flag is turned on.
You can decide whether or not you want a client disconnect to cause your script to be aborted. Sometimes it is handy to always have your scripts run to completion even if there is no remote browser receiving the output. The default behaviour is however for your script to be aborted when the remote client disconnects. This behaviour can be set via the ignore_user_abort php3.ini directive as well as through the corresponding php3_ignore_user_abort Apache .conf directive or with the ignore_user_abort() function. If you do not tell PHP to ignore a user abort and the user aborts, your script will terminate. The one exception is if you have registered a shutdown function using register_shutdown_function(). With a shutdown function, when the remote user hits his STOP button, the next time your script tries to output something PHP will detect that the connection has been aborted and the shutdown function is called. This shutdown function will also get called at the end of your script terminating normally, so to do something different in case of a client diconnect 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 php3.ini directive or the corresponding php3_max_execution_time Apache .conf directive as well as with the set_time_limit() function. When the timer expires the script will be aborted and as with the above client disconnect case, if a shutdown function has been registered it will be called. Within this shutdown function you can check to see if a timeout caused the shutdown function to be called by calling the connection_timeout() function. This function will return true 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_timeout() and connection_aborted() return true. You can also check both states in a single call by using the connection_status(). This function returns a bitfield of the active states. So, if both states are active it would return 3, for example.
Persistent connections are SQL 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 SQL link, they do not give you an ability to build up a transaction efficently, 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 each request comes in from a 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 serviced by a different child process than the first time. What a persistent connection does for you in this case it make it so each child process only needs to connect to your SQL server the first time that it serves a page that makes us of such a connection. When another page then requires a connection to the SQL server, it can reuse the connection that child established earlier.
The last method is to use PHP as a plug-in for a multithreaded web server. Currently this is only theoretical -- PHP does not yet work as a plug-in for any multithreaded web servers. Work is progressing on support for ISAPI, WSAPI, and NSAPI (on Windows), which will all allow PHP to be used as a plug-in on multithreaded servers like Netscape FastTrack, Microsoft's Internet Information Server (IIS), and O'Reilly's WebSite Pro. When this happens, the behavior will be 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 persistant 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), a database with only 32 connections may be rapidly swamped. Check your database documentation for information on handling abandoned or idle connections.
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!
(PHP3 >= 3.0.4, PHP4 )
apache_lookup_uri -- Perform a partial request for the specified URI and return all info about itclass 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 and returns this information in a class. The properties of the returned class 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 |
Note: Apache_lookup_uri() only works when PHP is installed as an Apache module.
string apache_note
(string note_name [, string note_value])
Apache_note() is an Apache-specific function which gets and sets values in a request's notes table. 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.
array getallheaders
(void)
This function returns an associative array of all the HTTP headers in the current request.
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 environment variables defined this way.
Example 1. getallheaders() Example
|
This example will display all the request headers for the current request.
Note: Getallheaders() is currently only supported when PHP runs as an Apache module.
int virtual
(string
filename)
Virtual() is an Apache-specific function which is equivalent 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. For PHP files, you need to use include() or require(); virtual() cannot be used to include a document which is itself a PHP file.
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.
array array
([mixed
...])
Returns an array of the parameters. The parameters can be given an index with the => operator.
Note: Array() is a language construct used to represent literal arrays, and not a regular function.
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
|
See also: list().
array array_count_values
(array input)
Array_count_values() returns an array using the values of the input array as keys and their frequency in input as values.
Example 1. Array_count_values() example
|
array array_diff
(array array1, array array2 [, array ...])
Array_diff() returns an array containing all the values of array1 that are not present in any of the other arguments. Note that keys are preserved.
Example 1. Array_diff() example
|
This makes $result have array ("blue");
See also array_intersect().
array array_flip
(array trans)
Array_flip() returns an array in flip order.
Example 1. Array_flip() example
|
array array_intersect
(array array1, array array2 [, array ...])
Array_intersect() returns an array containing all the values of array1 that are present in all the arguments. Note that keys are preserved.
Example 1. Array_intersect() example
|
This makes $result have array ("a" => "green", "red");
See also array_diff().
array array_keys
(array input [, mixed search_value])
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.
Example 1. Array_keys() example
|
See also array_values().
array array_merge
(array array1, array array2 [, array ...])
Array_merge() merges the elements of two 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 have the same numeric key, the later value will not overwrite the original value, but will be appended.
Example 1. array_merge() example
|
Resulting array will be array("color" => "green", 2, 4, "a", "b", "shape" => "trapezoid", 4).
See also array_merge_recursive().
array array_merge_recursive
(array array1, array array2 [,
array ...])
Array_merge_recursive() merges the elements of two or more arrays together so that the values of one are appended to the end of the previous one. It returns the resulting array.
If the input arrays have the same string keys, then the values for these keys are merged together into an array, and this is done recursively, so that if one of the values is an array itself, the function will merge it with a corresponding entry in another array too. If, however, the arrays have the same numeric key, the later value will not overwrite the original value, but will be appended.
Example 1. Array_merge_recursive() example
|
Resulting array will be array ("color" => array ("favorite" => array ("red", "green"), "blue"), 5, 10).
See also array_merge().
bool array_multisort
(array ar1 [, mixed arg [, mixed ... [, array ...]]])
Array_multisort() can be used to sort several arrays at once or a multi-dimensional array according by one of more dimensions. It maintains key association when sorting.
The input arrays are treated as columns of a table to be sorted by rows - this resembles the functionality of SQL ORDER BY clause. The first array is the primary one to sort by. The rows (values) in that array that compare the same are sorted by the next input array, and so on.
The argument structure of this function is a bit unusual, but flexible. The very first argument has to be an array. Subsequently, each argument can be either an array or a sorting flag from the following lists.
Sorting order flags:
SORT_ASC - sort in ascending order
SORT_DESC - sort in descending order
Sorting type flags:
SORT_REGULAR - compare items normally
SORT_NUMERIC - compare items numerically
SORT_STRING - compare items as strings
No two sorting flags of the same type can be specified after each array. The sortings flags specified after an array argument apply only to that array - they are reset to default SORT_ASC and SORT_REGULAR after before each new array argument.
Returns true on success, false on failure.
Example 1. Sorting multiple arrays
|
In this example, after sorting, the first array will contain 10, "a", 100, 100. The second array will contain 1, 1, 2, "3". The entries in the second array corresponding to the identical entries in the first array (100 and 100) were sorted as well.
Example 2. Sorting multi-dimensional array
|
In this example, after sorting, the first array will contain 10, 100, 100, "a" (it was sorted as strings in ascending order), and the second one will contain 1, 3, "2", 1 (sorted as numbers, in descending order).
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.
Example 1. Array_pad() example
|
mixed array_pop
(array
array)
Array_pop() pops and returns the last value of the array, shortening the array by one element.
Example 1. Array_pop() example
|
After this, $stack has only 2 elements: "orange" and "apple", and $fruit has "raspberry".
See also array_push(), array_shift(), and array_unshift().
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:
$array[] = $var; |
Returns the new number of elements in the array.
Example 1. Array_push() example
|
This example would result in $stack having 4 elements: 1, 2, "+", and 3.
See also: array_pop(), array_shift(), and array_unshift().
mixed array_rand
(array input [, int num_req])
Array_rand() is rather useful when you want to pick one or more random entries out of an array. It takes an input array and an optional argument num_req which specifies how many entries you want to pick - if not specified, it defaults to 1.
If you are picking only one entry, array_rand() returns the key for a random entry. Otherwise, it returns an array of keys for the random entries. This is done so that you can pick random keys as well as values out of the array.
Don't forget to call srand() to seed the random number generator.
Example 1. Array_rand() example
|
array array_reverse
(array array)
Array_reverse() takes input array and returns a new array with the order of the elements reversed.
Example 1. Array_reverse() example
|
This makes $result have array (array ("green", "red"), 4.0, "php").
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.
Example 1. Array_shift() example
|
This would result in $args having one element "-f" left, and $opt being "-v".
See also array_unshift(), array_push(), and array_pop().
array array_slice
(array array, int offset [, int length])
Array_slice() returns a sequence of elements from the array specified by the offset and length parameters.
If offset is positive, the sequence will start at that offset in the array. If offset is negative, the sequence will start that far from the end of the array.
If length is given and is positive, then the sequence will have that many elements in it. If length is given and is negative then the sequence will stop that many elements from the end of the array. If it is omitted, then the sequence will have everything from offset up until the end of the array.
Example 1. Array_slice() examples
|
See also array_splice().
array array_splice
(array input, int offset [, int length [, array replacement]])
Array_splice() removes the elements designated by offset and length from the input array, and replaces them with the elements of the replacement array, if supplied.
If offset is positive then the start of removed portion is at that offset from the beginning of the input array. If offset is negative then it starts that far from the end of the input array.
If length is omitted, removes everything from offset to the end of the array. If length is specified and is positive, then that many elements will be removed. If length is specified and is negative then the end of the removed portion will be that many elements from the end of the array. Tip: to remove everything from offset to the end of the array when replacement is also specified, use count($input) for length.
If replacement array is specified, then the removed elements are replaced with elements from this array. If offset and length are such that nothing is removed, then the elements from the replacement array are inserted in the place specified by the offset. Tip: if the replacement is just one element it is not necessary to put array() around it, unless the element is an array itself.
The following equivalences hold:
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)) $a[$x] = $y array_splice ($input, $x, 1, $y) |
Returns the array consisting of removed elements.
Example 1. Array_splice() examples
|
See also array_slice().
array array_unique
(array array)
Array_unique() takes input array and returns a new array without duplicate values. Note that keys are preserved.
Example 1. Array_unique() example
|
This makes $result have array ("a" => "green", "red", "blue");
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.
Returns the new number of elements in the array.
Example 1. Array_unshift() example
|
This would result in $queue having 5 elements: "p4", "p5", "p6", "p1", and "p3".
See also array_shift(), array_push(), and array_pop().
array array_values
(array input)
Array_values() returns all the values from the input array.
Example 1. Array_values() example
|
int array_walk
(array
arr, string func, mixed userdata)
Applies the function named by func to each element of arr. func will be passed array value as the first parameter and array key as the second parameter. If userdata is supplied, it will be passed as the third parameter to the user function.
If func requires more than two or three arguments, depending on userdata, a warning will be generated each time array_walk() calls func. These warnings may be suppressed by prepending the '@' sign to the array_walk() call, or by using error_reporting().
Note: If func needs to be working with the actual values of the array, specify that the first parameter of func should be passed by reference. Then any changes made to those elements will be made in the array itself.
Note: Passing the key and userdata to func was added in 4.0.
In PHP 4 reset() needs to be called as necessary since array_walk() does not reset the array by default.
Example 1. Array_walk() example
|
void arsort
(array
array [, int sort_flags])
This function sorts an array such that array indices maintain their correlation with the array elements they are associated with. This is used mainly when sorting associative arrays where the actual element order is significant.
Example 1. Arsort() example
|
This example would display:
fruits[a] = orange fruits[d] = lemon fruits[b] = banana fruits[c] = apple |
The fruits have been sorted in reverse alphabetical order, and the index associated with each element has been maintained.
You may modify the behavior of the sort using the optional parameter sort_flags, for details see sort().
void asort
(array
array [, int sort_flags])
This function sorts an array such that array indices maintain their correlation with the array elements they are associated with. This is used mainly when sorting associative arrays where the actual element order is significant.
Example 1. Asort() example
|
This example would display:
fruits[c] = apple fruits[b] = banana fruits[d] = lemon fruits[a] = orange |
The fruits have been sorted in alphabetical order, and the index associated with each element has been maintained.
You may modify the behavior of the sort using the optional parameter sort_flags, for details see sort().
array compact
(mixed
varname [, mixed ...])
Compact() takes a variable number of parameters. Each parameter can be either a string containing the name of the variable, or an array of variable names. The array can contain other arrays of variable names inside it; compact() handles it recursively.
For each of these, compact() looks for a variable with that name in the current symbol table and adds it to the output array such that the variable name becomes the key and the contents of the variable become the value for that key. In short, it does the opposite of extract(). It returns the output array with all the variables added to it.
Example 1. Compact() example
After this, $result will be array ("event" => "SIGGRAPH", "city" => "San Francisco", "state" => "CA"). |
See also extract().
int count
(mixed
var)
Returns the number of elements in var, which is typically an array (since anything else will have one element).
Returns 1 if the variable is not an array.
Returns 0 if the variable is not set.
Warning |
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. |
See also: sizeof(), isset(), and is_array().
mixed current
(array
array)
Every array has an internal pointer to its "current" element, which is initialized to the first element inserted into the array.
The current() function simply returns the array element that's currently being pointed by the internal pointer. It does not move the pointer in any way. If the internal pointer points beyond the end of the elements list, current() returns false.
Warning |
If the array contains empty elements (0 or "", the empty string) then this function will return false for these elements as well. This makes it impossible to determine if you are really at the end of the list in such an array using current(). To properly traverse an array that may contain empty elements, use the each() function. |
array each
(array
array)
Returns the current key and value pair from the array array and advances the array cursor. This pair is returned in a four-element array, with the keys 0, 1, key, and value. Elements 0 and key contain the key name of the array element, and 1 and value contain the data.
If the internal pointer for the array points past the end of the array contents, each() returns false.
Example 1. Each() examples
$bar now contains the following key/value pairs:
$bar now contains the following key/value pairs:
|
Each() is typically used in conjunction with list() to traverse an array; for instance, $HTTP_POST_VARS:
Example 2. Traversing $HTTP_POST_VARS with each()
|
After each() has executed, the array cursor will be left on the next element of the array, or on the last element if it hits the end of the array.
See also key(), list(), current(), reset(), next(), and prev().
void extract
(array
var_array [, int extract_type [, string prefix]])
This function is used to import variables from an array into the current symbol table. It takes associative array var_array and treats keys as variable names and values as variable values. For each key/value pair it will create a variable in the current symbol table, subject to extract_type and prefix parameters.
Extract() checks for colissions with existing variables. The way collisions are treated is determined by extract_type. It can be one of the following values:
If there is a collision, overwrite the existing variable.
If there is a collision, don't overwrite the existing variable.
If there is a collision, prefix the new variable with prefix.
Prefix all variables with prefix.
If extract_type is not specified, it is assumed to be EXTR_OVERWRITE.
Note that prefix is only required if extract_type is EXTR_PREFIX_SAME or EXTR_PREFIX_ALL.
Extract() checks each key to see if it constitues a valid variable name, and if it does only then does it proceed to import it.
A possible use for extract is to import into symbol table variables contained in an associative array returned by wddx_deserialize().
Example 1. Extract() example
|
The above example will produce:
blue, large, sphere, medium |
The $size wasn't overwritten, becaus 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 cause $size to have value "medium", and EXTR_PREFIX_ALL would result in new variables being named $wddx_color, $wddx_size, and $wddx_shape.
bool in_array
(mixed needle, array
haystack)
Searches haystack for needle and returns true if it is found in the array, false otherwise.
Example 1. In_array() example
|
int krsort
(array
array [, int sort_flags])
Sorts an array by key in reverse order, maintaining key to data correlations. This is useful mainly for associative arrays.
Example 1. Krsort() example
|
This example would display:
fruits[d] = lemon fruits[c] = apple fruits[b] = banana fruits[a] = orange |
You may modify the behavior of the sort using the optional parameter sort_flags, for details see sort().
int ksort
(array array
[, int sort_flags])
Sorts an array by key, maintaining key to data correlations. This is useful mainly for associative arrays.
Example 1. Ksort() example
|
This example would display:
fruits[a] = orange fruits[b] = banana fruits[c] = apple fruits[d] = lemon |
You may modify the behavior of the sort using the optional parameter sort_flags, for details see sort().
void list
(...);
Like array(), this is not really a function, but a language construct. list() is used to assign a list of variables in one operation.
Example 1. List() example
|
mixed next
(array
array)
Returns the array element in the next place that's pointed by the internal array pointer, or false if there are no more elements.
Next() behaves like current(), with one difference. It advances the internal array pointer one place forward before returning the element. That means it returns the next array element and advances the internal array pointer by one. If advancing the internal array pointer results in going beyond the end of the element list, next() returns false.
Warning |
If the array contains empty elements, or elements that have a key value of 0 then this function will return false for these elements as well. To properly traverse an array which may contain empty elements or elements with key values of 0 see the each() function. |
mixed prev
(array
array)
Returns the array element in the previous place that's pointed by the internal array pointer, or false if there are no more elements.
Warning |
If the array contains empty elements then this function will return false for these elements as well. To properly traverse an array which may contain empty elements see the each() function. |
Prev() behaves just like next(), except it rewinds the internal array pointer one place instead of advancing it.
array range
(int low,
int high)
Range() returns an array of integers from low to high, inclusive.
See shuffle() for an example of its use.
mixed reset
(array
array)
Reset() rewinds array's internal pointer to the first element.
Reset() returns the value of the first array element.
void rsort
(array
array [, int sort_flags])
This function sorts an array in reverse order (highest to lowest).
Example 1. Rsort() example
|
This example would display:
fruits[0] = orange fruits[1] = lemon fruits[2] = banana fruits[3] = apple |
The fruits have been sorted in reverse alphabetical order.
You may modify the behavior of the sort using the optional parameter sort_flags, for details see sort().
void shuffle
(array
array)
This function shuffles (randomizes the order of the elements in) an array.
Example 1. Shuffle() example
|
See also arsort(), asort(), ksort(), rsort(), sort() and usort().
void sort
(array array
[, int sort_flags])
This function sorts an array. Elements will be arranged from lowest to highest when this function has completed.
Example 1. Sort() example
|
This example would display:
fruits[0] = apple fruits[1] = banana fruits[2] = lemon fruits[3] = orange |
The fruits have been sorted in alphabetical order.
The optional second parameter sort_flags may be used to modify the sorting behavior using theese valies:
Sorting type flags:
SORT_REGULAR - compare items normally
SORT_NUMERIC - compare items numerically
SORT_STRING - compare items as strings
(PHP3 >= 3.0.4, PHP4 )
uasort -- Sort an array with a user-defined comparison function and maintain index associationvoid uasort
(array
array, function cmp_function)
This function sorts an array such that array indices maintain their correlation with the array elements they are associated with. This is used mainly when sorting associative arrays where the actual element order is significant. The comparison function is user-defined.
See also: usort(), uksort(), sort(), asort(), arsort(), ksort() and rsort().
void uksort
(array
array, function cmp_function)
This function 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.
Example 1. Uksort() example
|
This example would display:
20: twenty 10: ten 4: four 3: three |
See also: usort(), uasort(), sort(), asort(), arsort(), ksort() and rsort().
void usort
(array
array, string cmp_function)
This function will sort an array by its values using a user-supplied comparison function. If the array you wish to sort needs to be sorted by some non-trivial criteria, you should use this function.
The comparison function must return an integer less than, equal to, or greater than zero if the first argument is considered to be respectively less than, equal to, or greater than the second. If two members compare as equal, their order in the sorted array is undefined.
Example 1. Usort() example
|
This example would display:
0: 6 1: 5 2: 3 3: 2 4: 1 |
Note: Obviously in this trivial case the rsort() function would be more appropriate.
Example 2. Usort() example using multi-dimensional array
|
When sorting a multi-dimensional array, $a and $b contain references to the first index of the array.
This example would display:
$fruits[0]: apples $fruits[1]: grapes $fruits[2]: lemons |
Warning |
The underlying quicksort function in some C libraries (such as on Solaris systems) may cause PHP to crash if the comparison function does not return consistent values. |
See also: uasort(), uksort(), sort(), asort(), arsort(), ksort() and rsort().
The aspell() functions allows you to check the spelling on a word and offer suggestions.
Note: aspell works only with very old (up to .27.* or so) versions of aspell library. Neither this module, nor those versions of aspell library are supported any longer. If you want to use spell-checking capabilities in php, use pspell instead. It uses pspell library and works with newer versions of aspell.
You need the aspell library, available from: http://aspell.sourceforge.net/.
int aspell_new
(string
master, string personal)
Aspell_new() opens up a new dictionary and returns the dictionary link identifier for use in other aspell functions.
Example 1. Aspell_new()
|
boolean aspell_check
(int dictionary_link, string word)
Aspell_check() checks the spelling of a word and returns true if the spelling is correct, false if not.
Example 1. Aspell_check()
|
(PHP3 >= 3.0.7, PHP4 )
aspell_check-raw -- Check a word without changing its case or trying to trim itboolean aspell_check_raw
(int dictionary_link, string
word)
Aspell_check_raw() checks the spelling of a word, without changing its case or trying to trim it in any way and returns true if the spelling is correct, false if not.
Example 1. Aspell_check_raw()
|
array aspell_suggest
(int dictionary_link, string word)
Aspell_suggest() returns an array of possible spellings for the given word.
Example 1. Aspell_suggest()
|
string bcadd
(string
left operand, string right operand [, int scale])
Adds the left operand to the right operand and returns the sum in a string. The optional scale parameter is used to set the number of digits after the decimal place in the result.
See also bcsub().
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. The optional scale parameter is used to set the number of digits after the decimal place which will be used in the comparion. The return value is 0 if the two operands are equal. If the left operand is larger than the right operand the return value is +1 and if the left operand is less than the right operand the return value is -1.
string bcdiv
(string
left operand, string right operand [, int scale])
Divides the left operand by the right operand and returns the result. The optional scale sets the number of digits after the decimal place in the result.
See also bcmul().
string bcmod
(string
left operand, string modulus)
Get the modulus of the left operand using modulus.
See also bcdiv().
string bcmul
(string
left operand, string right operand [, int scale])
Multiply the left operand by the right operand and returns the result. The optional scale sets the number of digits after the decimal place in the result.
See also bcdiv().
string bcpow
(string
x, string y [, int scale])
Raise x to the power y. The optional scale can be used to set the number of digits after the decimal place in the result.
See also bcsqrt().
string bcscale
(int
scale)
This function sets the default scale parameter for all subsequent bc math functions that do not explicitly specify a scale parameter.
string bcsqrt
(string
operand, int scale)
Return the square root of the operand. The optional scale parameter sets the number of digits after the decimal place in the result.
See also bcpow().
string bcsub
(string
left operand, string right operand [, int scale])
Subtracts the right operand from the left operand and returns the result in a string. The optional scale parameter is used to set the number of digits after the decimal place in the result.
See also bcadd().
The calendar functions are only available if you have compiled the calendar extension in dl/calendar. Read dl/README for instructions on using it.
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 way earlier than any date most people would need to track (somewhere around 4000bc). 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 calendar systems visit http://genealogy.org/~scottlee/cal-overview.html. Excerpts from this page are included in these instructions, and are in quotes.
string jdtogregorian
(int julianday)
Converts Julian Day Count to a string containing the Gregorian date in the format of "month/day/year".
int gregoriantojd
(int
month, int day, int year)
Valid Range for Gregorian Calendar 4714 B.C. to 9999 A.D.
Although this software can handle dates all the way back to 4714 B.C., such use may not be meaningful. The Gregorian calendar was not instituted until October 15, 1582 (or October 5, 1582 in the Julian calendar). Some countries did not accept it until much later. For example, Britain converted in 1752, The USSR in 1918 and Greece in 1923. Most European countries used the Julian calendar prior to the Gregorian.
Example 1. Calendar functions
|
string jdtojulian
(int
julianday)
Converts Julian Day Count to a string containing the Julian Calendar Date in the format of "month/day/year".
int juliantojd
(int
month, int day, int year)
Valid Range for Julian Calendar 4713 B.C. to 9999 A.D.
Although this software 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.
int jewishtojd
(int
month, int day, int year)
Valid Range Although this software 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.
string jdtofrench
(int
month, int day, int year)
Converts a Julian Day Count to the French Republican Calendar.
(PHP3 , PHP4 )
FrenchToJD -- Converts a date from the French Republican Calendar to a Julian Day Countint 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.
string jdmonthname
(int julianday, int mode)
Returns a string containing a month name. mode tells this function which calendar to convert the Julian Day Count to, and what type of month names are to be returned.
Table 1. Calendar modes
Mode | Meaning |
---|---|
0 | Gregorian - abbreviated |
1 | Gregorian |
2 | Julian - abbreviated |
3 | Julian |
4 | Jewish |
5 | French Republican |
mixed jddayofweek
(int
julianday, int mode)
Returns the day of the week. Can return a string or an int depending on the mode.
Table 1. Calendar week modes
Mode | Meaning |
---|---|
0 | Returns the day number as an int (0=sunday, 1=monday, etc) |
1 | Returns string containing the day of week (english-gregorian) |
2 | Returns a string containing the abbreviated day of week (english-gregorian) |
(PHP3 >= 3.0.9, PHP4 >= 4.0RC2)
easter_date -- Get UNIX timestamp for midnight on Easter of a given yearint easter_date
(int
year)
Returns the UNIX timestamp corresponding to midnight on Easter of the given year. If no year is specified, the current year is assumed.
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).
Example 1. easter_date() example
|
The date of Easter Day was defined by the Council of Nicaea in AD325 as the Sunday after the first full moon which falls on or after the Spring Equinox. The Equinox is assumed to always fall on 21st March, so the calculation reduces to determining the date of the full moon and the date of the following Sunday. The algorithm used here was introduced around the year 532 by Dionysius Exiguus. Under the Julian Calendar (for years before 1753) a simple 19-year cycle is used to track the phases of the Moon. Under the Gregorian Calendar (for years after 1753 - devised by Clavius and Lilius, and introduced by Pope Gregory XIII in October 1582, and into Britain and its then colonies in September 1752) two correction factors are added to make the cycle more accurate.
(The code is based on a C program by Simon Kershaw, <webmaster@ely.anglican.org>)
See easter_days() for calculating Easter before 1970 or after 2037.
(PHP3 >= 3.0.9, PHP4 >= 4.0RC2)
easter_days -- Get number of days after March 21 on which Easter falls for a given yearint easter_days
(int
year)
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).
Example 1. Easter_date() example
|
The date of Easter Day was defined by the Council of Nicaea in AD325 as the Sunday after the first full moon which falls on or after the Spring Equinox. The Equinox is assumed to always fall on 21st March, so the calculation reduces to determining the date of the full moon and the date of the following Sunday. The algorithm used here was introduced around the year 532 by Dionysius Exiguus. Under the Julian Calendar (for years before 1753) a simple 19-year cycle is used to track the phases of the Moon. Under the Gregorian Calendar (for years after 1753 - devised by Clavius and Lilius, and introduced by Pope Gregory XIII in October 1582, and into Britain and its then colonies in September 1752) two correction factors are added to make the cycle more accurate.
(The code is based on a C program by Simon Kershaw, <webmaster@ely.anglican.org>)
See also easter_date().
int unixtojd
([int
timestamp])
Return the Julian Day for a UNIX timestamp (seconds since 1.1.1970), or for the current day if no timestamp is given.
See also jdtounix().
Note: This function is only available in PHP versions after PHP4RC1.
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 )
See also jdtounix().
Note: This function is only available in PHP versions after PHP4RC1.
These functions interface the CCVS API, allowing you to directly work with CCVS from your PHP scripts. CCVS is RedHat's solution to the "middle-man" in credit card processing. It lets you directly address the credit card clearing houses via your *nix box and a modem. Using the CCVS module for PHP, you can process credit cards directly through CCVS via your PHP Scripts. The following references will outline the process.
To enable CCVS Support in PHP, first verify your CCVS installation directory. You will then need to configure PHP with the --with-ccvs option. If you use this option without specifying the path to your CCVS installation, PHP Will attempt to look in the default CCVS Install location (/usr/local/ccvs). If CCVS is in a non-standard location, run configure with: --with-ccvs=$ccvs_path, where $ccvs_path is the path to your CCVS installation. Please note that CCVS support requires that $ccvs_path/lib and $ccvs_path/include exist, and include cv_api.h under the include directory and libccvs.a under the lib directory.
Additionally, a ccvsd process will need to be running for the configurations you intend to use in your PHP scripts. You will also need to make sure the PHP Processes are running under the same user as your CCVS was installed as (e.g. if you installed CCVS as user 'ccvs', your PHP processes must run as 'ccvs' as well.)
Additional information about CCVS can be found at http://www.redhat.com/products/ccvs.
This documentation section is being worked on. Until then, RedHat maintains slightly outdated but still useful documentation at http://www.redhat.com/products/ccvs/support/CCVS3.3docs/ProgPHP.html.
These functions are only available on the Windows version of PHP. These functions have been added in PHP4.
mixed com_invoke
(resource object, string function_name [, mixed function parameters,
...])
void com_propset
(resource object, string property, mixed value)
This function is an alias for com_propput().
These functions allow you to obtain information about classes and instance objects. You can obtain the name of the class to which a 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).
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
|
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
|
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 |
string get_class
(object obj)
This function returns the name of the class of which the object obj is an instance.
See also get_parent_class(), is_subclass_of()
string get_parent_class
(object obj)
This function returns the name of the parent class to the class of which the object obj is an instance.
See also get_class(), is_subclass_of()
array get_class_methods
(string class_name)
This function returns an array of method names defined for the class specified by class_name.
See also get_class_vars(), get_object_vars()
array get_class_vars
(string class_name)
This function will return an array of default properties of the class.
See also get_class_methods(), get_object_vars()
array get_object_vars
(object obj)
This function returns an associative array of object properties for the specified object obj.
See also get_class_methods(), get_class_vars()
(PHP4 >= 4.0b4)
is_subclass_of -- Determines if an object belongs to a subclass of the specified classbool is_subclass_of
(object obj, string superclass)
This function returns true if the object obj, belongs to a class which is a subclass of superclass, false otherwise.
See also get_class(), get_parent_class()
bool class_exists
(string class_name)
This function returns true if the class given by class_name has been defined, false otherwise.
bool method_exists
(object object, string method_name)
This function returns true if the method given by method_name has been defined for the given object, false otherwise.
array get_declared_classes
(void)
This function returns an array of the names of the declared classes in the current script.
Note: In PHP 4.0.1pl2, three extra classes are returned at the beginning of the array: stdClass (defined in Zend/zend.c), OverloadedTestClass (defined in ext/standard/basic_functions.c) and Directory (defined in ext/standard/dir.c).
mixed call_user_method
(string method_name, object obj [, mixed parameter [, mixed
...]])
Calls a the method referred by method_name from the user defined obj object. An example of usage is below, where we define a class, instantiate an object and use call_user_method() to call indirectly its print_info method.
<?php class Country { var $NAME; var $TLD; function Country($name, $tld) { $this->NAME = $name; $this->TLD = $tld; } function print_info($prestr="") { echo $prestr."Country: ".$this->NAME."\n"; echo $prestr."Top Level Domain: ".$this->TLD."\n"; } } $cntry = new Country("Peru","pe"); echo "* Calling the object method directly\n"; $cntry->print_info(); echo "\n* Calling the same method indirectly\n"; call_user_method ("print_info", $cntry, "\t"); ?> |
See also call_user_func().
ClibPDF lets you create PDF documents with PHP. It is available at FastIO but it isn't free software. You should definitely read the licence before you start playing with ClibPDF. If you cannot fullfil the licence agreement consider using pdflib by Thomas Merz, which is also very powerful. ClibPDF functionality and API is similar to Thomas Merz's pdflib but, according to FastIO, ClibPDF is faster and creates smaller documents. This may have changed with the new version 2.0 of pdflib. A simple benchmark (the pdfclock.c example from pdflib 2.0 turned into a php script) actually shows no difference in speed at all. The file size is also similar if compression is turned off. So, try them both and see which one does the job for you.
This documentation should be read alongside the ClibPDF manual since it explains the library in much greater detail.
Many functions in the native ClibPDF and the PHP module, as well as in pdflib, have the same name. All functions except for cpdf_open() take the handle for the document as their first parameter. Currently this handle is not used internally since ClibPDF does not support the creation of several PDF documents at the same time. Actually, you should not even try it, the results are unpredictable. I can't oversee what the consequences in a multi threaded environment are. According to the author of ClibPDF this will change in one of the next releases (current version when this was written is 1.10). If you need this functionality use the pdflib module.
Note: The function cpdf_set_font() has changed since PHP3 to support asian fonts. The encoding parameter is no longer an integer but a string.
One big advantage of ClibPDF over pdflib is the possibility to create the pdf document completely in memory without using temporary files. It also provides the ability to pass coordinates in a predefined unit length. This is a handy feature but can be simulated with pdf_translate().
Most of the functions are fairly easy to use. The most difficult part is probably creating a very simple PDF document at all. The following example should help you get started. It creates a document with one page. The page contains the text "Times-Roman" in an outlined 30pt font. The text is underlined.
Example 1. Simple ClibPDF Example
|
The pdflib distribution contains a more complex example which creates a series of pages with an analog clock. Here is that example converted into PHP using the ClibPDF extension:
Example 2. pdfclock example from pdflib 2.0 distribution
|
void cpdf_global_set_document_limits
(int maxpages, int
maxfonts, int maximages, int maxannotations, int maxobjects)
The cpdf_global_set_document_limits() function sets several document limits. This function has to be called before cpdf_open() to take effect. It sets the limits for any document open afterwards.
See also cpdf_open().
void cpdf_set_creator
(string creator)
The cpdf_set_creator() function sets the creator of a pdf document.
See also cpdf_set_subject(), cpdf_set_title(), cpdf_set_keywords().
void cpdf_set_title
(string title)
The cpdf_set_title() function sets the title of a pdf document.
See also cpdf_set_subject(), cpdf_set_creator(), cpdf_set_keywords().
void cpdf_set_subject
(string subject)
The cpdf_set_subject() function sets the subject of a pdf document.
See also cpdf_set_title(), cpdf_set_creator(), cpdf_set_keywords().
void cpdf_set_keywords
(string keywords)
The cpdf_set_keywords() function sets the keywords of a pdf document.
See also cpdf_set_title(), cpdf_set_creator(), cpdf_set_subject().
int cpdf_open
(int
compression, string filename)
The cpdf_open() function opens a new pdf document. The first parameter turns document compression on if it is unequal to 0. The second optional parameter sets the file in which the document is written. If it is omitted the document is created in memory and can either be written into a file with the cpdf_save_to_file() or written to standard output with cpdf_output_buffer().
Note: The return value will be needed in futher versions of ClibPDF as the first parameter in all other functions which are writing to the pdf document.
The ClibPDF library takes the filename "-" as a synonym for stdout. If PHP is compiled as an apache module this will not work because the way ClibPDF outputs to stdout does not work with apache. You can solve this problem by skipping the filename and using cpdf_output_buffer() to output the pdf document.
See also cpdf_close(), cpdf_output_buffer().
void cpdf_close
(int
pdf document)
The cpdf_close() function closes the pdf document. This should be the last function even after cpdf_finalize(), cpdf_output_buffer() and cpdf_save_to_file().
See also cpdf_open().
void cpdf_page_init
(int pdf document, int page number, int orientation, double height, double
width, double unit)
The cpdf_page_init() function starts a new page with height height and width width. The page has number page number and orientation orientation. orientation can be 0 for portrait and 1 for landscape. The last optional parameter unit sets the unit for the koordinate system. The value should be the number of postscript points per unit. Since one inch is equal to 72 points, a value of 72 would set the unit to one inch. The default is also 72.
See also cpdf_set_current_page().
void cpdf_finalize_page
(int pdf document, int page
number)
The cpdf_finalize_page() function ends the page with page number page number. This function is only for saving memory. A finalized page takes less memory but cannot be modified anymore.
See also cpdf_page_init().
void cpdf_finalize
(int pdf document)
The cpdf_finalize() function ends the document. You still have to call cpdf_close().
See also cpdf_close().
void cpdf_output_buffer
(int pdf document)
The cpdf_output_buffer() function outputs the pdf document to stdout. The document has to be created in memory which is the case if cpdf_open() has been called with no filename parameter.
See also cpdf_open().
void cpdf_save_to_file
(int pdf document, string filename)
The cpdf_save_to_file() function outputs the pdf document into a file if it has been created in memory. This function is not needed if the pdf document has been open by specifying a filename as a parameter of cpdf_open().
See also cpdf_output_buffer(), cpdf_open().
void cpdf_set_current_page
(int pdf document, int page
number)
The cpdf_set_current_page() function set the page on which all operations are performed. One can switch between pages until a page is finished with cpdf_finalize_page().
See also cpdf_finalize_page().
void cpdf_begin_text
(int pdf document)
The cpdf_begin_text() function starts a text section. It must be ended with cpdf_end_text().
Example 1. Text output
|
See also cpdf_end_text().
void cpdf_end_text
(int pdf document)
The cpdf_end_text() function ends a text section which was started with cpdf_begin_text().
Example 1. Text output
|
See also cpdf_begin_text().
void cpdf_show
(int
pdf document, string text)
The cpdf_show() function outputs the string in text at the current position.
See also cpdf_text(), cpdf_begin_text(), cpdf_end_text().
void cpdf_show_xy
(int
pdf document, string text, double x-koor, double y-koor, int mode)
The cpdf_show_xy() function outputs the string text at position with coordinates (x-koor, y-koor). The last optional parameter determines the unit length. If is 0 or omitted the default unit as specified for the page is used. Otherwise the koodinates are measured in postscript points disregarding the current unit.
Note: The function cpdf_show_xy() is identical to cpdf_text() without the optional parameters.
See also cpdf_text().
void cpdf_text
(int
pdf document, string text, double x-koor, double y-koor, int mode, double
orientation, int alignmode)
The cpdf_text() function outputs the string text at position with coordinates (x-koor, y-koor). The optional parameter determines the unit length. If is 0 or omitted the default unit as specified for the page is used. Otherwise the koodinates are measured in postscript points disregarding the current unit. The optional parameter orientation is the rotation of the text in degree. The optional parameter alignmode determines how the text is align. See the ClibPDF documentation for possible values.
See also cpdf_show_xy().
void cpdf_set_font
(int pdf document, string font name, double size, string encoding)
The cpdf_set_font() function sets the the current font face, font size and encoding. Currently only the standard postscript fonts are supported. The last parameter encoding can take the following values: "MacRomanEncoding", "MacExpertEncoding", "WinAnsiEncoding", and "NULL". "NULL" stands for the font's built-in encoding. See the ClibPDF Manual for more information, especially how to support asian fonts.
void cpdf_set leading
(int pdf document, double distance)
The cpdf_set_leading() function sets the distance between text lines. This will be used if text is output by cpdf_continue_text().
See also cpdf_continue_text().
void cpdf_set_text_rendering
(int pdf document, int
mode)
The cpdf_set_text_rendering() function determines how text is rendered. The possible values for mode are 0=fill text, 1=stroke text, 2=fill and stroke text, 3=invisible, 4=fill text and add it to cliping path, 5=stroke text and add it to clipping path, 6=fill and stroke text and add it to cliping path, 7=add it to clipping path.
void cpdf_set_horiz_scaling
(int pdf document, double
scale)
The cpdf_set_horiz_scaling() function sets the horizontal scaling to scale percent.
void cpdf_set_text_rise
(int pdf document, double
value)
The cpdf_set_text_rise() function sets the text rising to value units.
void cpdf_set_text_matrix
(int pdf document, array
matrix)
The cpdf_set_text_matrix() function sets a matrix which describes a transformation applied on the current text font.
void cpdf_set_text_pos
(int pdf document, double x-koor, double y-koor, int mode)
The cpdf_set_text_pos() function sets the position of text for the next cpdf_show() function call.
The last optional parameter mode determines the unit length. If is 0 or omitted the default unit as specified for the page is used. Otherwise the koodinates are measured in postscript points disregarding the current unit.
See also cpdf_show(), cpdf_text().
void cpdf_set_char_spacing
(int pdf document, double
space)
The cpdf_set_char_spacing() function sets the spacing between characters.
See also cpdf_set_word_spacing(), cpdf_set_leading().
void cpdf_set_word_spacing
(int pdf document, double
space)
The cpdf_set_word_spacing() function sets the spacing between words.
See also cpdf_set_char_spacing(), cpdf_set_leading().
void cpdf_continue_text
(int pdf document, string
text)
The cpdf_continue_text() function outputs the string in text in the next line.
See also cpdf_show_xy(), cpdf_text(), cpdf_set_leading(), cpdf_set_text_pos().
double cpdf_stringwidth
(int pdf document, string
text)
The cpdf_stringwidth() function returns the width of the string in text. It requires a font to be set before.
See also cpdf_set_font().
void cpdf_save
(int
pdf document)
The cpdf_save() function saves the current enviroment. It works like the postscript command gsave. Very useful if you want to translate or rotate an object without effecting other objects.
See also cpdf_restore().
void cpdf_restore
(int
pdf document)
The cpdf_restore() function restores the enviroment saved with cpdf_save(). It works like the postscript command grestore. Very useful if you want to translate or rotate an object without effecting other objects.
Example 1. Save/Restore
|
See also cpdf_save().
void cpdf_translate
(int pdf document, double x-koor, double y-koor, int mode)
The cpdf_translate() function set the origin of coordinate system to the point (x-koor, y-koor).
The last optional parameter determines the unit length. If is 0 or omitted the default unit as specified for the page is used. Otherwise the koodinates are measured in postscript points disregarding the current unit.
void cpdf_scale
(int
pdf document, double x-scale, double y-scale)
The cpdf_scale() function set the scaling factor in both directions.
void cpdf_rotate
(int
pdf document, double angle)
The cpdf_rotate() function set the rotation in degress to angle.
void cpdf_setflat
(int
pdf document, double value)
The cpdf_setflat() function set the flatness to a value between 0 and 100.
void cpdf_setlinejoin
(int pdf document, long value)
The cpdf_setlinejoin() function set the linejoin parameter between a value of 0 and 2. 0 = miter, 1 = round, 2 = bevel.
void cpdf_setlinecap
(int pdf document, int value)
The cpdf_setlinecap() function set the linecap parameter between a value of 0 and 2. 0 = butt end, 1 = round, 2 = projecting square.
void cpdf_setmiterlimit
(int pdf document, double
value)
The cpdf_setmiterlimit() function set the miter limit to a value greater or equal than 1.
void cpdf_setlinewidth
(int pdf document, double width)
The cpdf_setlinewidth() function set the line width to width.
void cpdf_setdash
(int
pdf document, double white, double black)
The cpdf_setdash() function set the dash pattern white white units and black black units. If both are 0 a solid line is set.
void cpdf_newpath
(int
pdf_document)
The cpdf_newpath() starts a new path on the document given by the pdf_document parameter.
void cpdf_moveto
(int
pdf document, double x-koor, double y-koor, int mode)
The cpdf_moveto() function set the current point to the coordinates x-koor and y-koor.
The last optional parameter determines the unit length. If is 0 or omitted the default unit as specified for the page is used. Otherwise the koodinates are measured in postscript points disregarding the current unit.
void cpdf_rmoveto
(int
pdf document, double x-koor, double y-koor, int mode)
The cpdf_rmoveto() function set the current point relative to the coordinates x-koor and y-koor.
The last optional parameter determines the unit length. If is 0 or omitted the default unit as specified for the page is used. Otherwise the koodinates are measured in postscript points disregarding the current unit.
See also cpdf_moveto().
void cpdf_curveto
(int
pdf document, double x1, double y1, double x2, double y2, double x3, double y3,
int mode)
The cpdf_curveto() function draws a Bezier curve from the current point to the point (x3, y3) using (x1, y1) and (x2, y2) as control points.
The last optional parameter determines the unit length. If is 0 or omitted the default unit as specified for the page is used. Otherwise the koodinates are measured in postscript points disregarding the current unit.
See also cpdf_moveto(), cpdf_rmoveto(), cpdf_rlineto(), cpdf_lineto().
void cpdf_lineto
(int
pdf document, double x-koor, double y-koor, int mode)
The cpdf_lineto() function draws a line from the current point to the point with coordinates (x-koor, y-koor).
The last optional parameter determines the unit length. If is 0 or omitted the default unit as specified for the page is used. Otherwise the koodinates are measured in postscript points disregarding the current unit.
See also cpdf_moveto(), cpdf_rmoveto(), cpdf_curveto().
void cpdf_rlineto
(int
pdf document, double x-koor, double y-koor, int mode)
The cpdf_rlineto() function draws a line from the current point to the relative point with coordinates (x-koor, y-koor).
The last optional parameter determines the unit length. If is 0 or omitted the default unit as specified for the page is used. Otherwise the koodinates are measured in postscript points disregarding the current unit.
See also cpdf_moveto(), cpdf_rmoveto(), cpdf_curveto().
void cpdf_circle
(int
pdf document, double x-koor, double y-koor, double radius, int mode)
The cpdf_circle() function draws a circle with center at point (x-koor, y-koor) and radius radius.
The last optional parameter determines the unit length. If is 0 or omitted the default unit as specified for the page is used. Otherwise the koodinates are measured in postscript points disregarding the current unit.
See also cpdf_arc().
void cpdf_arc
(int pdf
document, double x-koor, double y-koor, double radius, double start, double end,
int mode)
The cpdf_arc() function draws an arc with center at point (x-koor, y-koor) and radius radius, starting at angle start and ending at angle end.
The last optional parameter determines the unit length. If is 0 or omitted the default unit as specified for the page is used. Otherwise the koodinates are measured in postscript points disregarding the current unit.
See also cpdf_circle().
void cpdf_rect
(int
pdf document, double x-koor, double y-koor, double width, double height, int
mode)
The cpdf_rect() function draws a rectangle with its lower left corner at point (x-koor, y-koor). This width is set to widgth. This height is set to height.
The last optional parameter determines the unit length. If is 0 or omitted the default unit as specified for the page is used. Otherwise the koodinates are measured in postscript points disregarding the current unit.
void cpdf_closepath
(int pdf document)
The cpdf_closepath() function closes the current path.
void cpdf_stroke
(int
pdf document)
The cpdf_stroke() function draws a line along current path.
See also cpdf_closepath(), cpdf_closepath_stroke().
void cpdf_closepath_stroke
(int pdf document)
The cpdf_closepath_stroke() function is a combination of cpdf_closepath() and cpdf_stroke(). Than clears the path.
See also cpdf_closepath(), cpdf_stroke().
void cpdf_fill
(int
pdf document)
The cpdf_fill() function fills the interior of the current path with the current fill color.
See also cpdf_closepath(), cpdf_stroke(), cpdf_setgray_fill(), cpdf_setgray(), cpdf_setrgbcolor_fill(), cpdf_setrgbcolor().
void cpdf_fill_stroke
(int pdf document)
The cpdf_fill_stroke() function fills the interior of the current path with the current fill color and draws current path.
See also cpdf_closepath(), cpdf_stroke(), cpdf_fill(), cpdf_setgray_fill(), cpdf_setgray(), cpdf_setrgbcolor_fill(), cpdf_setrgbcolor().
void cpdf_closepath_fill_stroke
(int pdf
document)
The cpdf_closepath_fill_stroke() function closes, fills the interior of the current path with the current fill color and draws current path.
See also cpdf_closepath(), cpdf_stroke(), cpdf_fill(), cpdf_setgray_fill(), cpdf_setgray(), cpdf_setrgbcolor_fill(), cpdf_setrgbcolor().
void cpdf_clip
(int
pdf document)
The cpdf_clip() function clips all drawing to the current path.
void cpdf_setgray_fill
(int pdf document, double value)
The cpdf_setgray_fill() function sets the current gray value to fill a path.
See also cpdf_setrgbcolor_fill().
void cpdf_setgray_stroke
(int pdf document, double gray
value)
The cpdf_setgray_stroke() function sets the current drawing color to the given gray value.
See also cpdf_setrgbcolor_stroke().
void cpdf_setgray
(int
pdf document, double gray value)
The cpdf_setgray_stroke() function sets the current drawing and filling color to the given gray value.
See also cpdf_setrgbcolor_stroke(), cpdf_setrgbcolor_fill().
void cpdf_setrgbcolor_fill
(int pdf document, double red
value, double green value, double blue value)
The cpdf_setrgbcolor_fill() function sets the current rgb color value to fill a path.
See also cpdf_setrgbcolor_stroke(), cpdf_setrgbcolor().
void cpdf_setrgbcolor_stroke
(int pdf document, double red
value, double green value, double blue value)
The cpdf_setrgbcolor_stroke() function sets the current drawing color to the given rgb color value.
See also cpdf_setrgbcolor_fill(), cpdf_setrgbcolor().
void cpdf_setrgbcolor
(int pdf document, double red value, double green value, double blue
value)
The cpdf_setrgbcolor_stroke() function sets the current drawing and filling color to the given rgb color value.
See also cpdf_setrgbcolor_stroke(), cpdf_setrgbcolor_fill().
void cpdf_add_outline
(int pdf document, string text)
The cpdf_add_outline() function adds a bookmark with text text that points to the current page.
Example 1. Adding a page outline
|
void cpdf_set_page_animation
(int pdf document, int
transition, double duration)
The cpdf_set_page_animation() function set the transition between following pages.
The value of transition can be
0 for none, |
1 for two lines sweeping across the screen reveal the page, |
2 for multiple lines sweeping across the screen reveal the page, |
3 for a box reveals the page, |
4 for a single line sweeping across the screen reveals the page, |
5 for the old page dissolves to reveal the page, |
6 for the dissolve effect moves from one screen edge to another, |
7 for the old page is simply replaced by the new page (default) |
The value of duration is the number of seconds between page flipping.
int cpdf_open_jpeg
(int pdf document, string file name, double x-koor, double y-koor, double angle,
double width, double height, double x-scale, double y-scale, int
mode)
The cpdf_import_jpeg() function opens an image stored in the file with the name file name. The format of the image has to be jpeg. The image is placed on the current page at position (x-koor, y-koor). The image is rotated by angle degres.
The last optional parameter determines the unit length. If is 0 or omitted the default unit as specified for the page is used. Otherwise the koodinates are measured in postscript points disregarding the current unit.
See also cpdf_place_inline_image(),
void cpdf_place_inline_image
(int pdf document, int image,
double x-koor, double y-koor, double angle, double width, double height, int
mode)
The cpdf_place_inline_image() function places an image created with the php image functions on the page at postion (x-koor, y-koor). The image can be scaled at the same time.
The last optional parameter determines the unit length. If is 0 or omitted the default unit as specified for the page is used. Otherwise the koodinates are measured in postscript points disregarding the current unit.
See also cpdf_import_jpeg(),
void cpdf_add_annotation
(int pdf document, double llx,
double lly, double urx, double ury, string title, string content, int
mode)
The cpdf_add_annotation() adds a note with the lower left corner at (llx, lly) and the upper right corner at (urx, ury).
The last optional parameter determines the unit length. If is 0 or omitted the default unit as specified for the page is used. Otherwise the koodinates are measured in postscript points disregarding the current unit.
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.
In order to use the CURL functions you need to install the CURL package. PHP requires that you use CURL 7.0.2-beta or higher. PHP will not work with any version of CURL below version 7.0.2-beta.
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.
These functions have been added in PHP 4.0.2.
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_exec() and then you finish off your session using the curl_close(). Here is an example that uses the CURL functions to fetch the PHP homepage into a file:
Example 1. Using PHP's CURL module to fetch the PHP homepage
|
int curl_init
([string
url])
The curl_init() will initialize a new session and return a CURL handle for use with the curl_setopt(), curl_exec(), and curl_close() functions. If the optional url parameter is supplied then the CURLOPT_URL option will be set to the value of the parameter. You can manually set this using the curl_setopt() function.
Example 1. Initializing a new CURL session and fetching a webpage
|
See also: curl_close(), curl_setopt()
bool curl_setopt
(int
ch, string option, mixed value)
The curl_setopt() function will set options for a CURL session identified by the ch parameter. The option parameter is the option you want to set, and the value is the value of the option given by the option.
The value should be a long for the following options (specified in the option parameter):
CURLOPT_INFILESIZE: When you are uploading a file to a remote site, this option should be used to tell PHP what the expected size of the infile will be.
CURLOPT_VERBOSE: Set this option to a non-zero value if you want CURL to report everything that is happening.
CURLOPT_HEADER: Set this option to a non-zero value if you want the header to be included in the output.
CURLOPT_NOPROGRESS: Set this option to a non-zero value if you don't want PHP to display a progress meter for CURL transfers
Note: PHP automatically sets this option to a non-zero parameter, this should only be changed for debugging purposes.
CURLOPT_NOBODY: Set this option to a non-zero value if you don't want the body included with the output.
CURLOPT_FAILONERROR: Set this option to a non-zero value if you want PHP to fail silently if the HTTP code returned is greater than 300. The default behaviour is to return the page normally, ignoring the code.
CURLOPT_UPLOAD: Set this option to a non-zero value if you want PHP to prepare for an upload.
CURLOPT_POST: Set this option to a non-zero value if you want PHP to do a regular HTTP POST. This POST is a normal application/x-www-from-urlencoded kind, most commonly used by HTML forms.
CURLOPT_FTPLISTONLY: Set this option to a non-zero value and PHP will just list the names of an FTP directory.
CURLOPT_FTPAPPEND: Set this option to a non-zero value and PHP will append to the remote file instead of overwriting it.
CURLOPT_NETRC: Set this option to a non-zero value and PHP will scan your ~./netrc file to find your username and password for the remote site that you're establishing a connection with.
CURLOPT_FOLLOWLOCATION: Set this option to a non-zero value to follow any "Location: " header that the server sends as a part of the HTTP header (note this is recursive, PHP will follow as many "Location: " headers that it is sent.)
CURLOPT_PUT: Set this option a non-zero value to HTTP PUT a file. The file to PUT must be set with the CURLOPT_INFILE and CURLOPT_INFILESIZE.
CURLOPT_MUTE: Set this option to a non-zero value and PHP will be completely silent with regards to the CURL functions.
CURLOPT_TIMEOUT: Pass a long as a parameter that contains the maximum time, in seconds, that you'll allow the curl functions to take.
CURLOPT_LOW_SPEED_LIMIT: Pass a long as a parameter that contains the transfer speed in bytes per second that the transfer should be below during CURLOPT_LOW_SPEED_TIME seconds for PHP to consider it too slow and abort.
CURLOPT_LOW_SPEED_TIME: Pass a long as a parameter that contains the time in seconds that the transfer should be below the CURLOPT_LOW_SPEED_LIMIT for PHP to consider it too slow and abort.
CURLOPT_RESUME_FROM: Pass a long as a parameter that contains the offset, in bytes, that you want the transfer to start from.
CURLOPT_SSLVERSION: Pass a long as a parameter that contains the SSL version (2 or 3) to use. By default PHP will try and determine this by itself, although, in some cases you must set this manually.
CURLOPT_TIMECONDITION: Pass a long as a parameter that defines how the CURLOPT_TIMEVALUE is treated. You can set this parameter to TIMECOND_IFMODSINCE or TIMECOND_ISUNMODSINCE. This is a HTTP-only feature.
CURLOPT_TIMEVALUE: Pass a long as a parameter that is the time in seconds since January 1st, 1970. The time will be used as specified by the CURLOPT_TIMEVALUE option, or by default the TIMECOND_IFMODSINCE will be used.
The value parameter should be a string for the following values of the option parameter:
CURLOPT_URL: This is the URL that you want PHP to fetch. You can also set this option when initializing a session with the curl_init() function.
CURLOPT_USERPWD: Pass a string formatted in the [username]:[password] manner, for PHP to use for the connection. connection.
CURLOPT_PROXYUSERPWD: Pass a string formatted in the [username]:[password] format for connection to the HTTP proxy.
CURLOPT_RANGE: Pass the specified range you want. It should be in the "X-Y" format, where X or Y may be left out. The HTTP transfers also support several intervals, seperated with commas as in X-Y,N-M.
CURLOPT_POSTFIELDS: Pass a string containing the full data to post in an HTTP "POST" operation.
CURLOPT_REFERER: Pass a string containing the "referer" header to be used in an HTTP request.
CURLOPT_USERAGENT: Pass a string containing the "user-agent" header to be used in an HTTP request.
CURLOPT_FTPPORT: Pass a string containing the which will be used to get the IP address to use for the ftp "PORT" 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_COOKIE: Pass a string containing the content of the cookie to be set in the HTTP header.
CURLOPT_SSLCERT: Pass a string containing the filename of PEM formatted certificate.
CURLOPT_SSLCERTPASSWD: Pass a string containing the password required to use the CURLOPT_SSLCERT certificate.
CURLOPT_COOKIEFILE: Pass a string containing the name of the file containing the cookiee data. The cookie file can be in Netscape format, or just plain HTTP-style headers dumped into a file.
CURLOPT_CUSTOMREQUEST: Pass a string to be used instead of GET or HEAD when doing an HTTP request. This is useful for doing DELETE or another, more obscure, HTTP request.
Note: Don't do this without making sure your server supports the command first.
The following options expect a file descriptor that is obtained by using the fopen() function:
CURLOPT_FILE: The file where the output of your transfer should be placed, the default is STDOUT.
CURLOPT_INFILE: The file where the input of your transfer comes from.
CURLOPT_WRITEHEADER: The file to write the header part of the output into.
CURLOPT_STDERR: The file to write errors to instead of stderr.
bool curl_exec
(int
ch)
This function is should be called after you initialize a CURL session and all the options for the session are set. Its purpose is simply to execute the predefined CURL session (given by the ch).
void curl_close
(int
ch)
This functions closes a CURL session and frees all ressources. The CURL handle, ch, is also deleted.
These functions are only available if the interpreter has been compiled with the --with-cybercash=[DIR]. These functions have been added in PHP4.
array cybercash_encr
(string wmk, string sk, string inbuff)
The function returns an associative array with the elements "errcode" and, if "errcode" is false, "outbuff" (string), "outLth" (long) and "macbuff" (string).
array cybercash_decr
(string wmk, string sk, string inbuff)
The function returns an associative array with the elements "errcode" and, if "errcode" is false, "outbuff" (string), "outLth" (long) and "macbuff" (string).
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 subset of features modern databases such as Sleepycat Software's DB2 support. (This is not to be confused with IBM's DB2 software, which is supported through the ODBC functions.)
The behaviour of various aspects depend 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.
To add support for any of the following handlers, add the specified --with configure switch to your PHP configure line:
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. (--with-dbm)
Ndbm is a newer type and more flexible than dbm. It still has most of the arbitrary limits of dbm (therefore it is deprecated). (--with-ndbm)
Gdbm is the GNU database manager. (--with-gdbm)
DB2 is Sleepycat Software's DB2. It is described as "a programmatic toolkit that provides high-performance built-in database support for both standalone and client/server applications." (--with-db2)
DB3 is Sleepycat Software's DB3. (--with-db3)
Cdb is "a fast, reliable, lightweight package for creating and reading constant databases." It is from the author of qmail and can be found here. Since it is constant, we support only reading operations. (--with-cdb)
Example 1. DBA example
|
DBA is binary safe and does not have any arbitrary limits. 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
|
void dba_close
(int
handle)
Dba_close() closes the established database and frees all resources specified by handle.
handle is a database handle returned by dba_open().
Dba_close() does not return any value.
See also: dba_open() and dba_popen()
string dba_delete
(string key, int handle)
dba_delete() deletes the entry specified by key from the database specified with handle.
key is the key of the entry which is deleted.
handle is a database handle returned by dba_open().
dba_delete() returns true or false, if the entry is deleted or not deleted, respectively.
See also: dba_exists(), dba_fetch(), dba_insert(), and dba_replace().
bool dba_exists
(string key, int handle)
Dba_exists() checks whether the specified key exists in the database specified by handle.
Key is the key the check is performed for.
Handle is a database handle returned by dba_open().
Dba_exists() returns true or false, if the key is found or not found, respectively.
See also: dba_fetch(), dba_delete(), dba_insert(), and dba_replace().
string dba_fetch
(string key, int handle)
Dba_fetch() fetches the data specified by key from the database specified with handle.
Key is the key the data is specified by.
Handle is a database handle returned by dba_open().
Dba_fetch() returns the associated string or false, if the key/data pair is found or not found, respectively.
See also: dba_exists(), dba_delete(), dba_insert(), and dba_replace().
string dba_firstkey
(int handle)
Dba_firstkey() returns the first key of the database specified by handle and resets the internal key pointer. This permits a linear search through the whole database.
Handle is a database handle returned by dba_open().
Dba_firstkey() returns the key or false depending on whether it succeeds or fails, respectively.
See also: Dba_nextkey()
bool dba_insert
(string key, string value, int handle)
dba_insert() inserts the entry described with key and value into the database specified by handle. It fails, if an entry with the same key already exists.
key is the key of the entry to be inserted.
value is the value to be inserted.
handle is a database handle returned by dba_open().
dba_insert() returns true or false, depending on whether it succeeds of fails, respectively.
See also: dba_exists() dba_delete() dba_fetch() dba_replace()
string dba_nextkey
(int handle)
dba_nextkey() returns the next key of the database specified by handle and increments the internal key pointer.
handle is a database handle returned by dba_open().
dba_nextkey() returns the key or false depending on whether it succeeds or fails, respectively.
See also: dba_firstkey()
int dba_popen
(string
path, string mode, string handler [, ...])
dba_popen() establishes a persistent database instance for path with mode using handler.
path is commonly a regular path in your filesystem.
mode 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 is 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.
dba_popen() returns a positive handler id or false, in the case the open is successful or fails, respectively.
See also: dba_open() dba_close()
int dba_open
(string
path, string mode, string handler [, ...])
dba_open() establishes a database instance for path with mode using handler.
path is commonly a regular path in your filesystem.
mode 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 is 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.
dba_open() returns a positive handler id or false, in the case the open is successful or fails, respectively.
See also: dba_popen() dba_close()
bool dba_optimize
(int
handle)
dba_optimize() optimizes the underlying database specified by handle.
handle is a database handle returned by dba_open().
dba_optimize() returns true or false, if the optimization succeeds or fails, respectively.
See also: dba_sync()
bool dba_replace
(string key, string value, int handle)
dba_replace() replaces or inserts the entry described with key and value into the database specified by handle.
key is the key of the entry to be inserted.
value is the value to be inserted.
handle is a database handle returned by dba_open().
dba_replace() returns true or false, depending on whether it succeeds of fails, respectively.
See also: dba_exists() dba_delete() dba_fetch() dba_insert()
bool dba_sync
(int
handle)
dba_sync() synchronizes the database specified by handle. This will probably trigger a physical write to disk, if supported.
handle is a database handle returned by dba_open().
dba_sync() returns true or false, if the synchronization succeeds or fails, respectively.
See also: dba_optimize()
int checkdate
(int
month, int day, int year)
Returns true if the date given is valid; otherwise returns false. Checks the validity of the date formed by the arguments. A date is considered valid if:
year is between 0 and 32767 inclusive
month is between 1 and 12 inclusive
Day is within the allowed number of days for the given month. Leap years are taken into consideration.
string date
(string
format [, int timestamp])
Returns a string formatted according to the given format string using the given timestamp or the current local time if no timestamp is given.
The following characters are recognized in the format string:
a - "am" or "pm"
A - "AM" or "PM"
B - Swatch Internet time
d - day of the month, 2 digits with leading zeros; i.e. "01" to "31"
D - day of the week, textual, 3 letters; i.e. "Fri"
F - month, textual, long; i.e. "January"
g - hour, 12-hour format without leading zeros; i.e. "1" to "12"
G - hour, 24-hour format without leading zeros; i.e. "0" to "23"
h - hour, 12-hour format; i.e. "01" to "12"
H - hour, 24-hour format; i.e. "00" to "23"
i - minutes; i.e. "00" to "59"
I (capital i) - "1" if Daylight Savings Time, "0" otherwise.
j - day of the month without leading zeros; i.e. "1" to "31"
l (lowercase 'L') - day of the week, textual, long; i.e. "Friday"
L - boolean for whether it is a leap year; i.e. "0" or "1"
m - month; i.e. "01" to "12"
M - month, textual, 3 letters; i.e. "Jan"
n - month without leading zeros; i.e. "1" to "12"
s - seconds; i.e. "00" to "59"
S - English ordinal suffix, textual, 2 characters; i.e. "th", "nd"
t - number of days in the given month; i.e. "28" to "31"
T - Timezone setting of this machine; i.e. "MDT"
U - seconds since the epoch
w - day of the week, numeric, i.e. "0" (Sunday) to "6" (Saturday)
Y - year, 4 digits; i.e. "1999"
y - year, 2 digits; i.e. "99"
z - day of the year; i.e. "0" to "365"
Z - timezone offset in seconds (i.e. "-43200" to "43200")
Example 1. Date() example
|
It is possible to use date() and mktime() together to find dates in the future or the past.
Example 2. Date() and mktime() example
|
To format dates in other languages, you should use the setlocale() and strftime() functions.
array getdate
(int
timestamp)
Returns an associative array containing the date information of the timestamp as the following array elements:
"seconds" - seconds
"minutes" - minutes
"hours" - hours
"mday" - day of the month
"wday" - day of the week, numeric
"mon" - month, numeric
"year" - year, numeric
"yday" - day of the year, numeric; i.e. "299"
"weekday" - day of the week, textual, full; i.e. "Friday"
"month" - month, textual, full; i.e. "January"
array gettimeofday
(void)
This is an interface to gettimeofday(2). It returns an associative array containing the data returned from the system call.
"sec" - seconds
"usec" - microseconds
"minuteswest" - minutes west of Greenwich
"dsttime" - type of dst correction
string gmdate
(string
format, int timestamp)
Identical to the date() function except that the time returned is Greenwich Mean Time (GMT). For 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".
Example 1. Gmdate() example
|
See also date(), mktime(), and gmmktime().
int gmmktime
(int
hour, int minute, int second, int month, int day, int year [, int
is_dst])
Identical to mktime() except the passed parameters represents a GMT date.
(PHP3 >= 3.0.12, PHP4 >= 4.0RC2)
gmstrftime -- Format a GMT/CUT time/date according to locale settingsstring gmstrftime
(string format, int timestamp)
Behaves the same as strftime() except that the time returned is Greenwich Mean Time (GMT). For example, when run in Eastern Standard Time (GMT -0500), the first line below prints "Dec 31 1998 20:00:00", while the second prints "Jan 01 1999 01:00:00".
Example 1. Gmstrftime() example
|
See also strftime().
array localtime
([int
timestamp [, bool is_associative]])
The localtime() function returns an array identical to that of the structure returned by the C function call. The first argument to localtime() is the timestamp, if this is not given the current time is used. The second argument to the localtime() is the is_associative, if this is set to 0 or not supplied than the array is returned as a regular, numerically indexed array. If the argument is set to 1 then localtime() is an associative array containing all the different elements of the structure returned by the C function call to localtime. The names of the different keys of the associative array are as follows:
"tm_sec" - seconds
"tm_min" - minutes
"tm_hour" - hour
"tm_mday" - day of the month
"tm_mon" - month of the year
"tm_year" - Year, not y2k compliant
"tm_wday" - Day of the week
"tm_yday" - Day of the year
"tm_isdst" - Is daylight savings time in effect
string microtime
(void);
Returns the string "msec sec" where sec is the current time measured in the number of seconds since the Unix Epoch (0:00:00 January 1, 1970 GMT), and msec is the microseconds part. This function is only available on operating systems that support the gettimeofday() system call.
See also time().
int mktime
(int hour,
int minute, int second, int month, int day, int year [, int is_dst])
Warning: Note the strange order of arguments, which differs from the order of arguments in a regular UNIX mktime() call and which does not lend itself well to leaving out parameters from right to left (see below). It is a common error to mix these values up in a script.
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) 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.
Is_dst can be set to 1 if the time is during daylight savings time, 0 if it is not, or -1 (the default) if it is unknown whether the time is within daylight savings time or not.
Note: Is_dst was added in 3.0.10.
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".
Example 1. Mktime() example
|
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".
Example 2. Last day of next month
|
string strftime
(string format [, int timestamp])
Returns a string formatted according to the given format string using the given timestamp or the current local time if no timestamp is given. Month and weekday names and other language dependent strings respect the current locale set with setlocale().
The following conversion specifiers are recognized in the format string:
%a - abbreviated weekday name according to the current locale
%A - full weekday name according to the current locale
%b - abbreviated month name according to the current locale
%B - full month name according to the current locale
%c - preferred date and time representation for the current locale
%C - century number (the year divided by 100 and truncated to an integer, range 00 to 99)
%d - day of the month as a decimal number (range 00 to 31)
%D - same as %m/%d/%y
%e - day of the month as a decimal number, a single digit is preceded by a space (range ' 1' to '31')
%h - same as %b
%H - hour as a decimal number using a 24-hour clock (range 00 to 23)
%I - hour as a decimal number using a 12-hour clock (range 01 to 12)
%j - day of the year as a decimal number (range 001 to 366)
%m - month as a decimal number (range 1 to 12)
%M - minute as a decimal number
%n - newline character
%p - either `am' or `pm' according to the given time value, or the corresponding strings for the current locale
%r - time in a.m. and p.m. notation
%R - time in 24 hour notation
%S - second as a decimal number
%t - tab character
%T - current time, equal to %H:%M:%S
%u - weekday as a decimal number [1,7], with 1 representing Monday
%U - week number of the current year as a decimal number, starting with the first Sunday as the first day of the first week
%V - The ISO 8601:1988 week number of the current year as a decimal number, range 01 to 53, where week 1 is the first week that has at least 4 days in the current year, and with Monday as the first day of the week.
%W - week number of the current year as a decimal number, starting with the first Monday as the first day of the first week
%w - day of the week as a decimal, Sunday being 0
%x - preferred date representation for the current locale without the time
%X - preferred time representation for the current locale without the date
%y - year as a decimal number without a century (range 00 to 99)
%Y - year as a decimal number including the century
%Z - time zone or name or abbreviation
%% - a literal `%' character
Example 1. Strftime() example
|
See also setlocale() and mktime() and the Open Group specification of strftime().
int time
(void);
Returns the current time measured in the number of seconds since the Unix Epoch (January 1 1970 00:00:00 GMT).
See also date().
These functions allow you to access records stored in dBase-format (dbf) databases.
There is no support for indexes or memo fields. There is no support for locking, too. Two concurrent webserver processes modifying the same dBase file will very likely ruin your database.
Unlike SQL databases, dBase "databases" cannot change the database definition afterwards. Once the file is created, the database definition is fixed. There are no indexes that speed searching or otherwise organize your data. 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()().
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, since the file format is commonly understood with Windows spreadsheets and organizers. Import and export of data is about all that dBase support is good for.
int dbase_create
(string filename, array fields)
The fields parameter is an array of arrays, each array describing the format of one field in the database. Each field consists of a name, a character indicating the field type, a length, and a precision.
The types of fields available are:
Boolean. These do not have a length or precision.
Memo. (Note that these aren't supported by PHP.) These do not have a length or precision.
Date (stored as YYYYMMDD). These do not have a length or precision.
Number. These have both a length and a precision (the number of digits after the decimal point).
String.
If the database is successfully created, a dbase_identifier is returned, otherwise false is returned.
Example 1. Creating a dBase database file
|
int dbase_open
(string
filename, int flags)
The flags correspond to those for the open() system call. (Typically 0 means read-only, 1 means write-only, and 2 means read and write.)
Returns a dbase_identifier for the opened database, or false if the database couldn't be opened.
bool dbase_close
(int
dbase_identifier)
Closes the database associated with dbase_identifier.
bool dbase_pack
(int
dbase_identifier)
Packs the specified database (permanently deleting all records marked for deletion using dbase_delete_record().
bool dbase_add_record
(int dbase_identifier, array record)
Adds the data in the record to the database. If the number of items in the supplied record isn't equal to the number of fields in the database, the operation will fail and false will be returned.
bool dbase_replace_record
(int dbase_identifier, array
record, int dbase_record_number)
Replaces the data associated with the record record_number with the data in the record in the database. If the number of items in the supplied record is not equal to the number of fields in the database, the operation will fail and false will be returned.
dbase_record_number is an integer which spans from 1 to the number of records in the database (as returned by dbase_numrecords()).
bool dbase_delete_record
(int dbase_identifier, int
record)
Marks record to be deleted from the database. To actually remove the record from the database, you must also call dbase_pack().
array dbase_get_record
(int dbase_identifier, int record)
Returns the data from record in an array. The array is indexed starting at 0, and includes an associative member 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. (Dates are left as strings.)
(PHP3 >= 3.0.4, PHP4 )
dbase_get_record_with_names -- Gets a record from a dBase database as an associative arrayarray dbase_get_record_with_names
(int dbase_identifier, int
record)
Returns the data from record in an associative array. The array also includes an associative member 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. (Dates are left as strings.)
int dbase_numfields
(int dbase_identifier)
Returns the number of fields (columns) in the specified database. Field numbers are between 0 and dbase_numfields($db)-1, while record numbers are between 1 and dbase_numrecords($db).
Example 1. Using dbase_numfields()
|
These functions allow you to store records stored in a dbm-style database. This type of database (supported by the Berkeley DB, GDBM, and some system libraries, as well as a built-in flatfile library) stores key/value pairs (as opposed to the full-blown records supported by relational databases).
Example 1. DBM example
|
int dbmopen
(string
filename, string flags)
The first argument is the full-path filename of the DBM file to be opened and the second is the file open mode which is one of "r", "n", "c" or "w" for read-only, new (implies read-write, and most likely will truncate an already-existing database of the same name), create (implies read-write, and will not truncate an already-existing database of the same name) and read-write respectively.
Returns an identifer to be passed to the other DBM functions on success, or false on failure.
If NDBM support is used, NDBM will actually create filename.dir and filename.pag files. GDBM only uses one file, as does the internal flat-file support, and Berkeley DB creates a filename.db file. Note that PHP does its own file locking in addition to any file locking that may be done by the DBM library itself. PHP does not delete the .lck files it creates. It uses these files simply as fixed inodes on which to do the file locking. For more information on DBM files, see your Unix man pages, or obtain GNU's GDBM.
bool dbmexists
(int
dbm_identifier, string key)
Returns TRUE if there is a value associated with the key.
int dbminsert
(int
dbm_identifier, string key, string value)
Adds the value to the database with the specified key.
Returns -1 if the database was opened read-only, 0 if the insert was successful, and 1 if the specified key already exists. (To replace the value, use dbmreplace().)
bool dbmreplace
(int
dbm_identifier, string key, string value)
Replaces the value for the specified key in the database.
This will also add the key to the database if it didn't already exist.
bool dbmdelete
(int
dbm_identifier, string key)
Deletes the value for key in the database.
Returns false if the key didn't exist in the database.
string dbmfirstkey
(int dbm_identifier)
Returns the first key in the database. Note that no particular order is guaranteed since the database may be built using a hash-table, which doesn't guarantee any ordering.
string dbmnextkey
(int
dbm_identifier, string key)
Returns the next key after key. By calling dbmfirstkey() followed by successive calls to dbmnextkey() it is possible to visit every key/value pair in the dbm database. For example:
Example 1. Visiting every key/value pair in a DBM database
|
int chdir
(string
directory)
Changes PHP's current directory to directory. Returns FALSE if unable to change directory, TRUE otherwise.
new dir
(string
directory)
A pseudo-object oriented mechanism for reading a directory. The given directory is opened. Two properties are available once directory has been opened. The handle property can be used with other directory functions such as readdir(), rewinddir() and closedir(). The path property is set to path the directory that was opened. Three methods are available: read, rewind and close.
Example 1. Dir() Example
|
void closedir
(int
dir_handle)
Closes the directory stream indicated by dir_handle. The stream must have previously been opened by opendir().
int opendir
(string
path)
Returns a directory handle to be used in subsequent closedir(), readdir(), and rewinddir() calls.
string readdir
(int
dir_handle)
Returns the filename of the next file from the directory. The filenames are not returned in any particular order.
Example 1. List all files in the current directory
|
Note that readdir() will return the . and .. entries. If you don't want these, simply strip them out:
Example 2. List all files in the current directory and strip out . and ..
|
int dl
(string
library)
Loads the PHP extension defined in library. See also the extension_dir configuration directive.
These functions are only available if PHP was configured with --with-dom=[DIR], using the GNOME xml library. You will need at least libxml-2.0.0 (the beta version will not work). These functions have been added in PHP4.
This module defines the following constants:
Table 1. XML constants
Constant | Value | Description |
---|---|---|
XML_ELEMENT_NODE | 1 | |
XML_ATTRIBUTE_NODE | 2 | |
XML_TEXT_NODE | 3 | |
XML_CDATA_SECTION_NODE | 4 | |
XML_ENTITY_REF_NODE | 5 | |
XML_ENTITY_NODE | 6 | |
XML_PI_NODE | 7 | |
XML_COMMENT_NODE | 8 | |
XML_DOCUMENT_NODE | 9 | |
XML_DOCUMENT_TYPE_NODE | 10 | |
XML_DOCUMENT_FRAG_NODE | 11 | |
XML_NOTATION_NODE | 12 | |
XML_GLOBAL_NAMESPACE | 1 | |
XML_LOCAL_NAMESPACE | 2 |
This module defines a number of classes. The DOM XML functions return a parsed tree of the XML document with each node being an object belonging to one of these classes.
object xmldoc
(string
str)
The function parses the XML document in str and returns an object of class "Dom document", having the properties "doc" (resource), "version" (string) and "type" (long).
object xmldocfile
(string filename)
The function parses the XML document in the file named filename and returns an object of class "Dom document", having the properties "doc" (resource), "version" (string).
These functions allow read-only access to data stored in filePro databases.
filePro is a registered trademark of Fiserv, Inc. You can find more information about filePro at http://www.fileproplus.com/.
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.
string filepro_fieldname
(int field_number)
Returns the name of the field corresponding to field_number.
string filepro_fieldtype
(int field_number)
Returns the edit type of the field corresponding to field_number.
int filepro_fieldwidth
(int field_number)
Returns the width of the field corresponding to field_number.
string filepro_retrieve
(int row_number, int
field_number)
Returns the data from the specified location in the database.
int filepro_fieldcount
(void);
Returns the number of fields (columns) in the opened filePro database.
See also filepro().
int filepro_rowcount
(void);
Returns the number of rows in the opened filePro database.
See also filepro().
string basename
(string path)
Given a string containing a path to a file, this function will return the base name of the file.
On Windows, both slash (/) and backslash (\) are used as path separator character. In other environments, it is the forward slash (/).
Example 1. basename() example
|
See also: dirname()
int 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.
Returns true on success; otherwise returns false.
Note: This function does not work on Windows systems
int chmod
(string
filename, int mode)
Attempts to change the mode of the file specified by filename to that given in mode.
Note that mode is not automatically assumed to be an octal value, so strings (such as "g+w") will not work properly. To ensure the expected operation, you need to prefix mode with a zero (0):
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 |
Returns true on success and false otherwise.
Note: This function does not work on Windows systems
int 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.
Returns true on success; otherwise returns false.
See also chown() and chmod().
Note: This function does not work on Windows systems
void clearstatcache
(void);
Invoking the stat or lstat system call on most systems is quite expensive. Therefore, the result of the last call to any of the status functions (listed below) is stored for use on the next such call using the same filename. If you wish to force a new status check, for instance if the file is being checked many times and may change or disappear, use this function to clear the results of the last call from memory.
This value is only cached for the lifetime of a single request.
Affected functions include stat(), lstat(), file_exists(), is_writeable(), is_readable(), is_executable(), is_file(), is_dir(), is_link(), filectime(), fileatime(), filemtime(), fileinode(), filegroup(), fileowner(), filesize(), filetype(), and fileperms().
int copy
(string
source, string dest)
Makes a copy of a file. Returns true if the copy succeeded, false otherwise.
Example 1. Copy() example
|
See also: rename().
void delete
(string
file)
This is a dummy manual entry to satisfy those people who are looking for unlink() or unset() in the wrong place.
See also: unlink() to delete files, unset() to delete variables.
string dirname
(string
path)
Given a string containing a path to a file, this function will return the name of the directory.
On Windows, both slash (/) and backslash (\) are used as path separator character. In other environments, it is the forward slash (/).
Example 1. Dirname() example
|
See also: basename()
float diskfreespace
(string directory)
Given a string containing a directory, this function will return the number of bytes available on the corresponding filesystem or disk partition.
Example 1. diskfreespace() example
|
int fclose
(int
fp)
The file pointed to by fp is closed.
Returns true on success and false on failure.
The file pointer must be valid, and must point to a file successfully opened by fopen() or fsockopen().
int feof
(int
fp)
Returns true if the file pointer is at EOF or an error occurs; otherwise returns false.
The file pointer must be valid, and must point to a file successfully opened by fopen(), popen(), or fsockopen().
string fgetc
(int
fp)
Returns a string containing a single character read from the file pointed to by fp. Returns FALSE on EOF (as does feof()).
The file pointer must be valid, and must point to a file successfully opened by fopen(), popen(), or fsockopen().
See also fread(), fopen(), popen(), fsockopen(), and fgets().
array fgetcsv
(int fp,
int length [, string delimiter])
Similar to fgets() except that fgetcsv() parses the line it reads for fields in CSV format and returns an array containing the fields read. The field delimiter is a comma, unless you specifiy another delimiter with the optional third parameter.
Fp must be a valid file pointer to a file successfully opened by fopen(), popen(), or fsockopen()
Length must be greater than the longest line to be found in the CSV file (allowing for trailing line-end characters).
Fgetcsv() returns false on error, including end of file.
NB A blank line in a CSV file will be returned as an array comprising just one single null field, and will not be treated as an error.
Example 1. Fgetcsv() example - Read and print entire contents of a CSV file
|
string fgets
(int fp,
int length)
Returns a string of up to length - 1 bytes read from the file pointed to by fp. 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 an error occurs, returns false.
Common Pitfalls:
People used to the 'C' semantics of fgets should note the difference in how EOF is returned.
The file pointer must be valid, and must point to a file successfully opened by fopen(), popen(), or fsockopen().
A simple example follows:
Example 1. Reading a file line by line
|
See also fread(), fopen(), popen(), fgetc(), and fsockopen().
string fgetss
(int fp,
int length [, string allowable_tags])
Identical to fgets(), except that fgetss attempts to strip any HTML and PHP tags from the text it reads.
You can use the optional third parameter to specify tags which should not be stripped.
Note: allowable_tags was added in PHP 3.0.13, PHP4B3.
See also fgets(), fopen(), fsockopen(), popen(), and strip_tags().
array file
(string
filename [, int use_include_path])
Identical to readfile(), except that file() returns the file in an array. Each element of the array corresponds to a line in the file, with the newline still attached.
You can use the optional second parameter and set it to "1", if you want to search for the file in the include_path, too.
<?php // get a web page into an array and print it out $fcontents = file ('http://www.php.net'); while (list ($line_num, $line) = each ($fcontents)) { echo "<b>Line $line_num:</b> " . htmlspecialchars ($line) . "<br>\n"; } // get a web page into a string $fcontents = join ('', file ('http://www.php.net')); ?> |
See also readfile(), fopen(), and popen().
int file_exists
(string filename)
Returns true if the file specified by filename exists; false otherwise.
file_exists() will not work on remote files; the file to be examined must be accessible via the server's filesystem.
The results of this function are cached. See clearstatcache() for more details.
int fileatime
(string
filename)
Returns the time the file was last accessed, or false in case of an error. The time is returned as a Unix timestamp.
The results of this function are cached. See clearstatcache() for more details.
Note: The atime of a file is supposed to change whenever the data blocks of a file are being read. This can be costly performancewise when an appliation 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.
int filectime
(string
filename)
Returns the time the file was last changed, or false in case of an error. The time is returned as a Unix timestamp.
The results of this function are cached. See clearstatcache() for more details.
Note: In most Unix filesystem, a file is considered changed, when it's Inode data is changed, that is, when the permissions, the owner, the group or other metadata from the Inode is written to. See also filemtime() (this is what you want to use when you want to create "Last Modified" footers on web pages) and fileatime().
Note: In some Unix texts the ctime of a file is being referred to as the creation time of the file. This is wrong. There is no creation time for Unix files in most Unix filesystems.
int filegroup
(string
filename)
Returns the group ID of the owner of the file, or false in case of an error. The group ID is returned in numerical format, use posix_getgrgid() to resolve it to a group name.
The results of this function are cached. See clearstatcache() for more details.
Note: This function does not work on Windows systems
int fileinode
(string
filename)
Returns the inode number of the file, or false in case of an error.
The results of this function are cached. See clearstatcache() for more details.
Note: This function does not work on Windows systems
int filemtime
(string
filename)
Returns the time the file was last modified, or false in case of an error. The time is returned as a Unix timestamp.
The results of this function are cached. See clearstatcache() for more details.
Note: 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. Use date() on the result of this function to get a printable modification date for use in page footers.
int fileowner
(string
filename)
Returns the user ID of the owner of the file, or false in case of an error. The user ID is returned in numerical format, use posix_getpwuid() to resolve it to a username.
The results of this function are cached. See clearstatcache() for more details.
Note: This function does not work on Windows systems
int fileperms
(string
filename)
Returns the permissions on the file, or false in case of an error.
The results of this function are cached. See clearstatcache() for more details.
int filesize
(string
filename)
Returns the size of the file, or false in case of an error.
The results of this function are cached. See clearstatcache() for more details.
string filetype
(string filename)
Returns the type of the file. Possible values are fifo, char, dir, block, link, file, and unknown.
Returns false if an error occurs.
The results of this function are cached. See clearstatcache() for more details.
bool flock
(int fp,
int operation [, int wouldblock])
PHP supports a portable way of locking complete files in an advisory way (which means all accessing programs have to use the same way of locking or it will not work).
flock() operates on fp which must be an open file pointer. operation is one of the following values:
To acquire a shared lock (reader), set operation to LOCK_SH (set to 1 prior to PHP 4.0.1).
To acquire an exclusive lock (writer), set operation to LOCK_EX (set to 2 prior to PHP 4.0.1).
To release a lock (shared or exclusive), set operation to LOCK_UN (set to 3 prior to PHP 4.0.1).
If you don't want flock() to block while locking, add LOCK_NB (4 prior to PHP 4.0.1) to operation.
Flock() allows you to perform a simple reader/writer model which can be used on virtually every platform (including most Unices and even Windows). The optional 3rd argument is set to true if the lock would block (EWOULDBLOCK errno condition)
Flock() returns true on success and false on error (e.g. when a lock could not be acquired).
int fopen
(string
filename, string mode [, int use_include_path])
If filename begins with "http://" (not case sensitive), an HTTP 1.0 connection is opened to the specified server and a file pointer is returned to the beginning of the text of the response. A 'Host:' header is sent with the request in order to handle name-based virtual hosts.
Does not handle HTTP redirects, so you must include trailing slashes on directories.
If filename begins with "ftp://" (not case sensitive), an ftp connection to the specified server is opened and a pointer to the requested file is returned. If the server does not support passive mode ftp, this will fail. You can open files for either reading and writing via ftp (but not both simultaneously).
If filename is one of "php://stdin", "php://stdout", or "php://stderr", the corresponding stdio stream will be opened. (This was introduced in PHP 3.0.13; in earlier versions, a filename such as "/dev/stdin" or "/dev/fd/0" must be used to access the stdio streams.)
If filename begins with anything else, the file will be opened from the filesystem, and a file pointer to the file opened is returned.
If the open fails, the function returns false.
mode may be any of the following:
'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.
You can use the optional third parameter and set it to "1", if you want to search for the file in the include_path, too.
Example 1. Fopen() example
|
If you are experiencing problems with reading and writing to files and you're using the server module version of PHP, remember to make sure that the files and directories you're using are accessible to the server process.
On the Windows platform, be careful to escape any backslashes used in the path to the file, or use forward slashes.
$fp = fopen ("c:\\data\\info.txt", "r"); |
See also fclose(), fsockopen(), and popen().
int fpassthru
(int
fp)
Reads to EOF on the given file pointer and writes the results to standard output.
If an error occurs, fpassthru() returns false.
The file pointer must be valid, and must point to a file successfully opened by fopen(), popen(), or fsockopen(). The file is closed when fpassthru() is done reading it (leaving fp useless).
If you just want to dump the contents of a file to stdout you may want to use the readfile(), which saves you the fopen() call.
See also readfile(), fopen(), popen(), and fsockopen()
int fputs
(int fp,
string str [, int length])
Fputs() is an alias to fwrite(), and is identical in every way. Note that the length parameter is optional and if not specified the entire string will be written.
string fread
(int fp,
int length)
Fread() reads up to length bytes from the file pointer referenced by fp. Reading stops when length bytes have been read or EOF is reached, whichever comes first.
// get contents of a file into a string $filename = "/usr/local/something.txt"; $fd = fopen ($filename, "r"); $contents = fread ($fd, filesize ($filename)); fclose ($fd); |
See also fwrite(), fopen(), fsockopen(), popen(), fgets(), fgetss(), fscanf(), file(), and fpassthru().
mixed fscanf
(int
handle, string format [, string var1...])
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. 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.
Example 1. Fscanf() Example
|
Example 2. users.txt
|
See also fread(), fgets(), fgetss(), sscanf(), printf(), and sprintf().
int fseek
(int fp, int
offset [, int whence])
Sets the file position indicator for the file referenced by fp.The new position, measured in bytes from the beginning of the file, is obtained by adding offset to the position specified by whence, whose values are defined as follows:
SEEK_SET - Set position equal to offset bytes. |
SEEK_CUR - Set position to current location plus offset. |
SEEK_END - Set position to end-of-file plus offset. |
If whence is not specified, it is assumed to be SEEK_SET.
Upon success, returns 0; otherwise, returns -1. Note that seeking past EOF is not considered an error.
May not be used on file pointers returned by fopen() if they use the "http://" or "ftp://" formats.
Note: The whence argument was added after PHP 4.0 RC1.
array fstat
(int
fp)
Gathers the statistics of the file opened by the file pointer fp. This function is similar to the stat() function except that it operates on an open file pointer instead of a filename.
Returns an array with the statistics of the file with the following elements:
device
inode
number of links
user id of owner
group id owner
device type if inode device *
size in bytes
time of last access
time of last modification
time of last change
blocksize for filesystem I/O *
number of blocks allocated
The results of this function are cached. See clearstatcache() for more details.
int ftell
(int
fp)
Returns the position of the file pointer referenced by fp; i.e., its offset into the file stream.
If an error occurs, returns false.
The file pointer must be valid, and must point to a file successfully opened by fopen() or popen().
int ftruncate
(int fp,
int size)
Takes the filepointer, fp, and truncates the file to length, size. This function returns true on success and false on failure.
int fwrite
(int fp,
string string [, int length])
fwrite() writes the contents of string to the file stream pointed to by fp. 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.
See also fread(), fopen(), fsockopen(), popen(), and fputs().
int set_file_buffer
(int fp, int buffer)
set_file_buffer() sets the buffering for write operations on the given filepointer fp to buffer bytes. If buffer is 0 then write operations are unbuffered.
The function returns 0 on success, or EOF if the request cannot be honored.
Note that the default for any fopen with calling set_file_buffer is 8K.
See also fopen().
bool is_dir
(string
filename)
Returns true if the filename exists and is a directory.
The results of this function are cached. See clearstatcache() for more details.
bool is_executable
(string filename)
Returns true if the filename exists and is executable.
The results of this function are cached. See clearstatcache() for more details.
bool is_file
(string
filename)
Returns true if the filename exists and is a regular file.
The results of this function are cached. See clearstatcache() for more details.
bool is_link
(string
filename)
Returns true if the filename exists and is a symbolic link.
The results of this function are cached. See clearstatcache() for more details.
See also is_dir() and is_file().
Note: This function does not work on Windows systems
bool is_readable
(string filename)
Returns true if the filename exists and is readable.
Keep in mind that PHP may be accessing the file as the user id that the web server runs as (often 'nobody'). Safe mode limitations are not taken into account.
The results of this function are cached. See clearstatcache() for more details.
See also is_writeable().
bool is_writeable
(string filename)
Returns true if the filename exists and is writeable. The filename argument may be a directory name allowing you to check if a directory is writeable.
Keep in mind that PHP may be accessing the file as the user id that the web server runs as (often 'nobody'). Safe mode limitations are not taken into account.
The results of this function are cached. See clearstatcache() for more details.
See also is_readable().
int link
(string
target, string link)
Link() creates a hard link.
See also the symlink() to create soft links, and readlink() along with linkinfo().
Note: This function does not work on Windows systems
int linkinfo
(string
path)
Linkinfo() returns the st_dev field of the UNIX C stat structure returned by the lstat system call. This function is used to verify if a link (pointed to by path) really exists (using the same method as the S_ISLNK macro defined in stat.h). Returns 0 or FALSE in case of error.
See also symlink(), link(), and readlink().
Note: This function does not work on Windows systems
int mkdir
(string
pathname, int mode)
Attempts to create the directory specified by pathname.
Note that you probably want to specify the mode as an octal number, which means it should have a leading zero.
mkdir ("/path/to/my/dir", 0700); |
Returns true on success and false on failure.
See also rmdir().
int pclose
(int
fp)
Closes a file pointer to a pipe opened by popen().
The file pointer must be valid, and must have been returned by a successful call to popen().
Returns the termination status of the process that was run.
See also popen().
int popen
(string
command, string mode)
Opens a pipe to a process executed by forking the command given by command.
Returns a file pointer identical to that returned by fopen(), except that it is unidirectional (may only be used for reading or writing) and must be closed with pclose(). This pointer may be used with fgets(), fgetss(), and fputs().
If an error occurs, returns false.
$fp = popen ("/bin/ls", "r"); |
See also pclose().
int readfile
(string
filename [, int use_include_path])
Reads a file and writes it to standard output.
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.
If filename begins with "http://" (not case sensitive), an HTTP 1.0 connection is opened to the specified server and the text of the response is written to standard output.
Does not handle HTTP redirects, so you must include trailing slashes on directories.
If filename begins with "ftp://" (not case sensitive), an ftp connection to the specified server is opened and the requested file is written to standard output. If the server does not support passive mode ftp, this will fail.
If filename begins with neither of these strings, the file will be opened from the filesystem and its contents written to standard output.
You can use the optional second parameter and set it to "1", if you want to search for the file in the include_path, too.
See also fpassthru(), file(), fopen(), include(), require(), and virtual().
string readlink
(string path)
Readlink() does the same as the readlink C function and returns the contents of the symbolic link path or 0 in case of error.
See also symlink(), readlink() and linkinfo().
Note: This function does not work on Windows systems
int rename
(string
oldname, string newname)
Attempts to rename oldname to newname.
Returns true on success and false on failure.
int rewind
(int
fp)
Sets the file position indicator for fp to the beginning of the file stream.
If an error occurs, returns 0.
The file pointer must be valid, and must point to a file successfully opened by fopen().
int rmdir
(string
dirname)
Attempts to remove the directory named by pathname. The directory must be empty, and the relevant permissions must permit. this.
If an error occurs, returns 0.
See also mkdir().
array stat
(string
filename)
Gathers the statistics of the file named by filename.
Returns an array with the statistics of the file with the following elements:
device
inode
inode protection mode
number of links
user id of owner
group id owner
device type if inode device *
size in bytes
time of last access
time of last modification
time of last change
blocksize for filesystem I/O *
number of blocks allocated
The results of this function are cached. See clearstatcache() for more details.
array lstat
(string
filename)
Gathers the statistics of the file or symbolic link named by filename. This function is identical to the stat() function except that if the filename parameter is a symbolic link, the status of the symbolic link is returned, not the status of the file pointed to by the symbolic link.
Returns an array with the statistics of the file with the following elements:
device
inode
number of links
user id of owner
group id owner
device type if inode device *
size in bytes
time of last access
time of last modification
time of last change
blocksize for filesystem I/O *
number of blocks allocated
The results of this function are cached. See clearstatcache() for more details.
string realpath
(string path)
realpath() expands all symbolic links and resolves references to '/./', '/../' and extra '/' characters in the input path and return the canonicalized absolute pathname. The resulting path will have no symbolic link, '/./' or '/../' components.
Example 1. realpath() example
|
int symlink
(string
target, string link)
symlink() creates a symbolic link from the existing target with the specified name link.
See also link() to create hard links, and readlink() along with linkinfo().
Note: This function does not work on Windows systems.
string tempnam
(string
dir, string prefix)
Creates a unique temporary filename in the specified directory. If the directory does not exist, tempnam() may generate a filename in the system's temporary directory.
The behaviour of the tempnam() function is 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.
Returns the new temporary filename, or the null string on failure.
Example 1. Tempnam() example
|
See also tmpfile().
int tmpfile
(void)
Creates a temporary file with an unique name in write mode, returning a file handle similar to the one returned by fopen() The file is automatically removed when closed (using fclose()), or when the script ends.
For details, consult your system documentation on the tmpfile(3) function, as well as the stdio.h header file.
See also tempnam().
int touch
(string
filename [, int time])
Attempts to set the modification time of the file named by filename to the value given by time. If the option time is not given, uses the present time.
If the file does not exist, it is created.
Returns true on success and false otherwise.
Example 1. Touch() example
|
int umask
(int
mask)
Umask() sets PHP's umask to mask & 0777 and returns the old umask. When PHP is being used as a server module, the umask is restored when each request is finished.
Umask() without arguments simply returns the current umask.
int unlink
(string
filename)
Deletes filename. Similar to the Unix C unlink() function.
Returns 0 or FALSE on an error.
See also rmdir() for removing directories.
Note: This function may not work on Windows systems.
Forms Data Format (FDF) is a format for handling forms within PDF documents. You should read the documentation at http://partners.adobe.com/asn/developer/acrosdk/forms.html for more information on what FDF is and how it is used in general.
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. They should be in fdftk-dir/include and fdftk-dir/lib. This will not be the case if you just unpack the FdfTk distribution.
The general idea of FDF is similar to HTML forms. The diffence 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 whicht 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 documention 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..
The following examples shows just the evaluation of form data.
Example 1. Evaluating a FDF document
|
int fdf_open
(string
filename)
The fdf_open() function opens a file with form data. This file must contain the data as returned from a PDF form. Currently, the file has to be created 'manually' by using fopen() and writing the content of HTTP_FDF_DATA with fwrite() into it. A mechanism like for HTML form data where for each input field a variable is created does not exist.
Example 1. Accessing the form data
|
See also fdf_close().
void fdf_close
(int
fdf_document)
The fdf_close() function closes the FDF document.
See also fdf_open().
int fdf_create
(void
)
The fdf_create() creates a new FDF document. This function is needed if one would like to populate input fields in a PDF document with data.
Example 1. Populating a PDF document
|
See also fdf_close(), fdf_save(), fdf_open().
int fdf_save
(string
filename)
The fdf_save() function saves a FDF document. The FDF Toolkit provides a way to output the document to stdout if the parameter filename is '.'. This does not work if PHP is used as an apache module. In such a case one will have to write to a file and use e.g. fpassthru(). to output it.
See also fdf_close() and example for fdf_create().
string fdf_get_value
(int fdf_document, string fieldname)
The fdf_get_value() function returns the value of a field.
See also fdf_set_value().
void fdf_set_value
(int fdf_document, string fieldname, string value, int isName)
The fdf_set_value() function sets the value of a field. The last parameter determines if the field value is to be converted to a PDF Name (isName = 1) or set to a PDF String (isName = 0).
See also fdf_get_value().
string fdf_next_field_name
(int fdf_document, string
fieldname)
The fdf_next_field_name() function returns the name of the field after the field in fieldname or the field name of the first field if the second paramter is NULL.
See also fdf_set_field(), fdf_get_field().
void fdf_set_ap
(int
fdf_document, string field_name, int face, string filename, int
page_number)
The fdf_set_ap() function sets the appearance of a field (i.e. the value of the /AP key). The possible values of face are 1=FDFNormalAP, 2=FDFRolloverAP, 3=FDFDownAP.
void fdf_set_status
(int fdf_document, string status)
The fdf_set_status() sets the value of the /STATUS key.
See also fdf_get_status().
string fdf_get_status
(int fdf_document)
The fdf_get_status() returns the value of the /STATUS key.
See also fdf_set_status().
void fdf_set_file
(int
fdf_document, string filename)
The fdf_set_file() sets the value of the /F key. The /F key is just a reference to a PDF form which is to be populated with data. In a web environment it is a URL (e.g. http:/testfdf/resultlabel.pdf).
See also fdf_get_file() and example for fdf_create().
string fdf_get_file
(int fdf_document)
The fdf_set_file() returns the value of the /F key.
See also fdf_set_file().
void fdf_set_flags
(int fdf_document, string fieldname, int whichFlags, int newFlags)
The fdf_set_flags() sets certain flags of the given field fieldname.
See also fdf_set_opt().
void fdf_set_opt
(int
fdf_document, string fieldname, int element, string str1, string
str2)
The fdf_set_opt() sets options of the given field fieldname.
See also fdf_set_flags().
void fdf_set_submit_form_action
(int fdf_document, string
fieldname, int trigger, string script, int flags)
The fdf_set_submit_form_action() sets a submit form action for the given field fieldname.
See also fdf_set_javascript_action().
void fdf_set_javascript_action
(int fdf_document, string
fieldname, int trigger, string script)
The fdf_set_javascript_action() sets a javascript action for the given field fieldname.
See also fdf_set_submit_form_action().
FTP stands for File Transfer Protocol.
The following constants are defined when using the FTP module: FTP_ASCII, and FTP_BINARY.
int ftp_connect
(string host [, int port])
Returns a FTP stream on success, false on error.
ftp_connect() opens up a FTP connection to the specified host. The port parameter specifies an alternate port to connect to. If it is omitted or zero, then the default FTP port, 21, will be used.
int ftp_login
(int
ftp_stream, string username, string password)
Returns true on success, false on error.
Logs in the given FTP stream.
int ftp_cdup
(int
ftp_stream)
Returns true on success, false on error.
Changes to the parent directory.
int ftp_chdir
(int
ftp_stream, string directory)
Returns true on success, false on error.
Changes to the specified directory.
string ftp_mkdir
(int
ftp_stream, string directory)
Returns the newly created directory name on success, false on error.
Creates the specified directory.
int ftp_rmdir
(int
ftp_stream, string directory)
Returns true on success, false on error.
Removes the specified directory.
int ftp_nlist
(int
ftp_stream, string directory)
Returns an array of filenames on success, false on error.
(PHP3 >= 3.0.13, PHP4 >= 4.0b4)
ftp_rawlist -- Returns a detailed list of files in the given directory.int ftp_rawlist
(int
ftp_stream, string directory)
ftp_rawlist() executes the FTP LIST command, and returns the result as an array. Each array 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.
(PHP3 >= 3.0.13, PHP4 >= 4.0b4)
ftp_systype -- Returns the system type identifier of the remote FTP server.int ftp_pasv
(int
ftp_stream, int pasv)
Returns true on success, false on error.
ftp_pasv() turns on passive mode if the pasv parameter is true (it turns off passive mode if pasv is false.) In passive mode, data connections are initiated by the client, rather than by the server.
int ftp_get
(int
ftp_stream, string local_file, string remote_file, int mode)
Returns true on success, false on error.
ftp_get() retrieves remote_file from the FTP server, and saves it to local_file locally. The transfer mode specified must be either FTP_ASCII or FTP_BINARY.
(PHP3 >= 3.0.13, PHP4 >= 4.0b4)
ftp_fget -- Downloads a file from the FTP server and saves to an open file.int ftp_fget
(int
ftp_stream, int fp, string remote_file, int mode)
Returns true on success, false on error.
ftp_fget() retrieves remote_file from the FTP server, and writes it to the given file pointer, fp. The transfer mode specified must be either FTP_ASCII or FTP_BINARY.
int ftp_put
(int
ftp_stream, string remote_file, string local_file, int mode)
Returns true on success, false on error.
ftp_put() stores local_file on the FTP server, as remote_file. The transfer mode specified must be either FTP_ASCII or FTP_BINARY.
int ftp_fput
(int
ftp_stream, string remote_file, int fp, int mode)
Returns true on success, false on error.
ftp_fput() uploads the data from the file pointer fp until end of file. The results are stored in remote_file on the FTP server. The transfer mode specified must be either FTP_ASCII or FTP_BINARY.
int ftp_size
(int
ftp_stream, string remote_file)
Returns the file size on success, or -1 on error.
ftp_size() returns the size of a file. If an error occurs, of if the file does not exist, -1 is returned. Not all servers support this feature.
int ftp_mdtm
(int
ftp_stream, string remote_file)
Returns a UNIX timestamp on success, or -1 on error.
ftp_mdtm() checks the last-modified time for a file, and returns it as a UNIX timestamp. If an error occurs, or the file does not exist, -1 is returned. Note that not all servers support this feature.
int ftp_rename
(int
ftp_stream, string from, string to)
Returns true on success, false on error.
ftp_rename() renames the file specified by from to the new name to
int ftp_delete
(int
ftp_stream, string path)
Returns true on success, false on error.
ftp_delete() deletes the file specified by path from the FTP server.
int ftp_site
(int
ftp_stream, string cmd)
Returns true on success, false on error.
ftp_site() sends the command specified by cmd 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.
The gettext functions implement a NLS (Native Language Support) API which can be used to internationalize your PHP applications. Please see the GNU gettext documentation for a thorough explanation of these functions.
string bindtextdomain
(string domain, string directory)
The bindtextdomain() function sets the path for a domain.
string dcgettext
(string domain, string message, int category)
This function allows you to override the current domain for a single message lookup. It also allows you to specify a category.
string dgettext
(string domain, string message)
The dgettext() function allows you to override the current domain for a single message lookup.
string gettext
(string
message)
This function returns a translated string if one is found in the translation table, or the submitted message if not found. You may use an underscore character as an alias to this function.
Example 1. Gettext()-check
|
int textdomain
([string library])
This function sets the domain to search within when calls are made to gettext(), usually the named after an application. The previous default domain is returned. Call it with no parameters to get the current setting without changing it.
These functions let you manipulate the output sent back to the remote browser right down to the HTTP protocol level.
int header
(string
string)
The Header() function is used at the top of an HTML file to send raw HTTP header strings. See the HTTP 1.1 Specification for more information on raw http headers. Note: Remember that the Header() function must be called before any actual output is sent either by normal HTML tags or from PHP. It is a very common error to read code with include() or with auto_prepend and have spaces or empty lines in this code that force output before header() is called.
There are two special-case header calls. The first is the "Location" header. Not only does it send this header back to the browser, it also returns a REDIRECT status code to Apache. From a script writer's point of view this should not be important, but for people who understand Apache internals it is important to understand.
header ("Location: http://www.php.net"); /* Redirect browser to PHP web site */ exit; /* Make sure that code below does not get executed when we redirect. */ |
The second special-case is any header that starts with the string, "HTTP/" (case is not significant). For example, if you have your ErrorDocument 404 Apache directive pointed to a PHP script, it would be a good idea to make sure that your PHP script is actually generating a 404. The first thing you do in your script should then be:
header ("HTTP/1.0 404 Not Found"); |
PHP scripts often generate dynamic HTML 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
header ("Expires: Mon, 26 Jul 1997 05:00:00 GMT"); // Date in the past header ("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT"); // always modified header ("Cache-Control: no-cache, must-revalidate"); // HTTP/1.1 header ("Pragma: no-cache"); // HTTP/1.0 |
See also headers_sent()
boolean headers_sent
(void)
This function returns true if the HTTP headers have already been sent, false otherwise.
See also header()
int setcookie
(string
name [, string value [, int expire [, string path [, string domain [, int
secure]]]]])
Setcookie() defines a cookie to be sent along with the rest of the header information. Cookies must be sent before any other headers are sent (this is a restriction of cookies, not PHP). This requires you to place calls to this function before any <html> or <head> tags.
All the arguments except the name argument are optional. If only the name argument is present, the cookie by that name will be deleted from the remote client. You may also replace any argument with an empty string ("") in order to skip that argument. The expire and secure arguments are integers and cannot be skipped with an empty string. Use a zero (0) instead. The expire argument is a regular Unix time integer as returned by the time() or mktime() functions. The secure indicates that the cookie should only be transmitted over a secure HTTPS connection.
Common Pitfalls:
Cookies will not become visible until the next loading of a page that the cookie should be visible for.
Cookies must be deleted with the same parameters as they were set with.
In PHP3, multiple calls to setcookie() in the same script will be performed in reverse order. If you are trying to delete one cookie before inserting another you should put the insert before the delete. In PHP4, multiple calls to setcookie() are performed in the order called.
Some examples follow how to send cookies:
Example 1. Setcookie() send examples
|
Examples follow how to delete cookies send in previous example:
Example 2. setcookie() delete examples
|
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. To see the contents of our test cookie in a script, simply use one of the following examples:
echo $TestCookie; echo $HTTP_COOKIE_VARS["TestCookie"]; |
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:
setcookie ("cookie[three]", "cookiethree"); setcookie ("cookie[two]", "cookietwo"); setcookie ("cookie[one]", "cookieone"); if (isset ($cookie)) { while (list ($name, $value) = each ($cookie)) { echo "$name == $value<br>\n"; } } |
For more information on cookies, see Netscape's cookie specification at http://www.netscape.com/newsref/std/cookie_spec.html.
Microsoft Internet Explorer 4 with Service Pack 1 applied does not correctly deal with cookies that have their path parameter set.
Netscape Communicator 4.05 and Microsoft Internet Explorer 3.x appear to handle cookies incorrectly when the path and time are not set.
Hyperwave has been developed at IICM in Graz. It started with the name Hyper-G and changed to Hyperwave when it was commercialised (If I remember properly it was in 1996).
Hyperwave is not free software. The current version, 4.1, is available at http://www.hyperwave.com/. A time limited version can be ordered for free (30 days).
Hyperwave is an information system similar to a database (HIS, Hyperwave Information Server). Its focus is the storage and management of documents. A document can be any possible piece of data that may as well be stored in file. Each document is accompanied by its object record. The object record contains meta data for the document. The meta data is a list of attributes which can be extended by the user. Certain attributes are always set by the Hyperwave server, other may be modified by the user. An attribute is a name/value pair of the form name=value. The complete object record contains as many of those pairs as the user likes. The name of an attribute does not have to be unique, e.g. a title may appear several times within an object record. This makes sense if you want to specify a title in several languages. In such a case there is a convention, that each title value is preceded by the two letter language abbreviation followed by a colon, e.g. 'en:Title in English' or 'ge:Titel in deutsch'. Other attributes like a description or keywords are potential candidates. You may also replace the language abbreviation by any other string as long as it separated by colon from the rest of the attribute value.
Each object record has native a string representation with each name/value pair separated by a newline. The Hyperwave extension also knows a second representation which is an associated array with the attribute name being the key. Multilingual attribute values itself form another associated array with the key being the language abbreviation. Actually any multiple attribute forms an associated array with the string left to the colon in the attribute value being the key. (This is not fully implemented. Only the attributes Title, Description and Keyword are treated properly yet.)
Besides the documents, all hyper links contained in a document are stored as object records as well. Hyper links which are in a document will be removed from it and stored as individual objects, when the document is inserted into the database. The object record of the link contains information about where it starts and where it ends. In order to gain the original document you will have to retrieve the plain document without the links and the list of links and reinsert them (The functions hw_pipedocument() and hw_gettext() do this for you. The advantage of separating links from the document is obvious. Once a document to which a link is pointing to changes its name, the link can easily be modified accordingly. The document containing the link is not affected at all. You may even add a link to a document without modifying the document itself.
Saying that hw_pipedocument() and hw_gettext() do the link insertion automatically is not as simple as it sounds. Inserting links implies a certain hierarchy of the documents. On a web server this is given by the file system, but Hyperwave has its own hierarchy and names do not reflect the position of an object in that hierarchy. Therefore creation of links first of all requires a mapping from the Hyperwave hierarchy and namespace into a web hierarchy respective web namespace. The fundamental difference between Hyperwave and the web is the clear distinction between names and hierarchy in Hyperwave. The name does not contain any information about the objects position in the hierarchy. In the web the name also contains the information on where the object is located in the hierarchy. This leads to two possibles ways of mapping. Either the Hyperwave hierarchy and name of the Hyperwave object is reflected in the URL or the name only. To make things simple the second approach is used. Hyperwave object with name 'my_object' is mapped to 'http://host/my_object' disregarding where it resides in the Hyperwave hierarchy. An object with name 'parent/my_object' could be the child of 'my_object' in the Hyperwave hierarchy, though in a web namespace it appears to be just the opposite and the user might get confused. This can only be prevented by selecting reasonable object names.
Having made this decision a second problem arises. How do you involve PHP? The URL http://host/my_object will not call any PHP script unless you tell your web server to rewrite it to e.g. 'http://host/php3_script/my_object' and the script 'php3_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. '_'. to be continued.
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: An 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 associated array with all attributes of an object. The key is the attribute name. If an attribute occurs more than once in an object record it will result in another indexed or associated array. Attributes which are language depended (like the title, keyword, description) will form an associated array with the key set to the language abbreviation. 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 optimised for HTML documents but may be used for any format.
Several functions which return an array of object records do also return an associated array with statistical information about them. The array is the last element of the object record array. The statistical array contains the following entries:
Number of object records with attribute PresentationHints set to Hidden.
Number of object records with attribute PresentationHints set to CollectionHead.
Number of object records with attribute PresentationHints set to FullCollectionHead.
Index in array of object records with attribute PresentationHints set to CollectionHead.
Index in array of object records with attribute PresentationHints set to FullCollectionHead.
Total: Number of object records.
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 I will assume that the Apache server will only serve as a Hyperwave web interface. 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 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] |
RewriteRule ^/hw/(.*) /usr/local/apache/htdocs/hw/$1 [L] |
RewriteEngine on |
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.
There are still some things todo:
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.
strin hw_array2objrec
(array object_array)
Converts an object_array into an object record. Multiple attributes like 'Title' in different languages are treated properly.
See also hw_objrec2array().
array hw_children
(int
connection, int objectID)
Returns an array of object ids. Each id belongs to a child of the collection with ID objectID. The array contains all children both documents and collections.
array hw_childrenobj
(int connection, int objectID)
Returns an array of object records. Each object record belongs to a child of the collection with ID objectID. The array contains all children both documents and collections.
int hw_close
(int
connection)
Returns false if connection is not a valid connection index, otherwise true. Closes down the connection to a Hyperwave server with the given connection index.
int hw_connect
(string
host, int port, string username, string password)
Opens a connection to a Hyperwave server and returns a connection index on success, or false if the connection could not be made. Each of the arguments should be a quoted string, except for the port number. The username and password arguments are optional and can be left out. In such a case no identification with the server will be done. It is similar to identify as user anonymous. This function returns a connection index that is needed by other Hyperwave functions. You can have multiple connections open at once. Keep in mind, that the password is not encrypted.
See also hw_pConnect().
int hw_cp
(int
connection, array object_id_array, int destination id)
Copies the objects with object ids as specified in the second parameter to the collection with the id destination id.
The value return is the number of copied objects.
See also hw_mv().
int hw_deleteobject
(int connection, int object_to_delete)
Deletes the object with the given object id in the second parameter. It will delete all instances of the object.
Returns TRUE if no error occurs otherwise FALSE.
See also hw_mv().
int hw_docbyanchor
(int connection, int anchorID)
Returns an th object id of the document to which anchorID belongs.
string hw_docbyanchorobj
(int connection, int
anchorID)
Returns an th object record of the document to which anchorID belongs.
string hw_documentattributes
(int hw_document)
Returns the object record of the document.
See also hw_DocumentBodyTag(), hw_DocumentSize().
string hw_documentbodytag
(int hw_document)
Returns the BODY tag of the document. If the document is an HTML document the BODY tag should be printed before the document.
See also hw_DocumentAttributes(), hw_DocumentSize().
string hw_documentcontent
(int hw_document)
Returns the content of the document. If the document is an HTML document the content is everything after the BODY tag. Information from the HEAD and BODY tag is in the stored in the object record.
See also hw_DocumentAttributes(), hw_DocumentSize(), hw_DocumentSetContent().
string hw_documentsetcontent
(int hw_document, string
content)
Sets or replaces the content of the document. If the document is an HTML document the content is everything after the BODY tag. Information from the HEAD and BODY tag is in the stored in the object record. If you provide this information in the content of the document too, the Hyperwave server will change the object record accordingly when the document is inserted. Probably not a very good idea. If this functions fails the document will retain its old content.
See also hw_DocumentAttributes(), hw_DocumentSize(), hw_DocumentContent().
int hw_documentsize
(int hw_document)
Returns the size in bytes of the document.
See also hw_DocumentBodyTag(), hw_DocumentAttributes().
string hw_errormsg
(int connection)
Returns a string containing the last error message or 'No Error'. If false is returned, this function failed. The message relates to the last command.
int hw_edittext
(int
connection, int hw_document)
Uploads the text document to the server. The object record of the document may not be modified while the document is edited. This function will only works for pure text documents. It will not open a special data connection and therefore blocks the control connection during the transfer.
See also hw_PipeDocument(), hw_FreeDocument(), hw_DocumentBodyTag(), hw_DocumentSize(), hw_OutputDocument(), hw_GetText().
int hw_error
(int
connection)
Returns the last error number. If the return value is 0 no error has occurred. The error relates to the last command.
int hw_free_document
(int hw_document)
Frees the memory occupied by the Hyperwave document.
array hw_getparentsobj
(int connection, int objectID)
Returns an indexed array of object ids. Each object id belongs to a parent of the object with ID objectID.
array hw_getparentsobj
(int connection, int objectID)
Returns an indexed array of object records plus an associated array with statistical information about the object records. The associated array is the last entry of the returned array. Each object record belongs to a parent of the object with ID objectID.
array hw_getchildcoll
(int connection, int objectID)
Returns an array of object ids. Each object ID belongs to a child collection of the collection with ID objectID. The function will not return child documents.
See also hw_GetChildren(), hw_GetChildDocColl().
array hw_getchildcollobj
(int connection, int
objectID)
Returns an array of object records. Each object records belongs to a child collection of the collection with ID objectID. The function will not return child documents.
See also hw_ChildrenObj(), hw_GetChildDocCollObj().
int hw_getremote
(int
connection, int objectID)
Returns a remote document. Remote documents in Hyperwave notation are documents retrieved from an external source. Common remote documents are for example external web pages or queries in a database. In order to be able to access external sources throught remote documents Hyperwave introduces the HGI (Hyperwave Gateway Interface) which is similar to the CGI. Currently, only ftp, http-servers and some databases can be accessed by the HGI. Calling hw_GetRemote() returns the document from the external source. If you want to use this function you should be very familiar with HGIs. You should also consider to use PHP instead of Hyperwave to access external sources. Adding database support by a Hyperwave gateway should be more difficult than doing it in PHP.
See also hw_GetRemoteChildren().
int hw_getremotechildren
(int connection, string object
record)
Returns the children of a remote document. Children of a remote document are remote documents itself. This makes sense if a database query has to be narrowed and is explained in Hyperwave Programmers' Guide. If the number of children is 1 the function will return the document itself formated 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 exactely such an object record looks like is up to the HGI. If you want to use this function you should be very familiar with HGIs. You should also consider to use PHP instead of Hyperwave to access external sources. Adding database support by a Hyperwave gateway should be more difficult than doing it in PHP.
See also hw_GetRemote().
array hw_getsrcbydestobj
(int connection, int
objectID)
Returns the object records of all anchors pointing to the object with ID objectID. The object can either be a document or an anchor of type destination.
See also hw_GetAnchors().
array hw_getobject
(int connection, [int|array] objectID, string query)
Returns the object record for the object with ID objectID if the second parameter is an integer. If the second parameter is an array of integer the function will return an array of object records. In such a case the last parameter is also evaluated which is a query string.
The query string has the following syntax:
<expr> ::= "(" <expr> ")" |
"!" <expr> | /* NOT */
<expr> "||" <expr> | /* OR */
<expr> "&&" <expr> | /* AND */
<attribute> <operator> <value>
<attribute> ::= /* any attribute name (Title, Author, DocumentType ...) */
<operator> ::= "=" | /* equal */
"<" | /* less than (string compare) */
">" | /* greater than (string compare) */
"~" /* regular expression matching */
The query allows to further select certain objects from the list of given objects. Unlike the other query functions, this query may use not indexed attributes. How many object records are returned depends on the query and if access to the object is allowed.
See also hw_GetAndLock(), hw_GetObjectByQuery().
string hw_getandlock
(int connection, int objectID)
Returns the object record for the object with ID objectID. It will also lock the object, so other users cannot access it until it is unlocked.
See also hw_Unlock(), hw_GetObject().
int hw_gettext
(int
connection, int objectID [, mixed rootID/prefix])
Returns the document with object ID objectID. If the document has anchors which can be inserted, they will be inserted already. The optional parameter rootID/prefix can be a string or an integer. If it is an integer it determines how links are inserted into the document. The default is 0 and will result in links that are constructed from the name of the link's destination object. This is useful for web applications. If a link points to an object with name 'internet_movie' the HTML link will be <A HREF="/internet_movie">. The actual location of the source and destination object in the document hierachy is disregarded. You will have to set up your web browser, to rewrite that URL to for example '/my_script.php3/internet_movie'. 'my_script.php3' will have to evaluate $PATH_INFO and retrieve the document. All links will have the prefix '/my_script.php3/'. If you do not want this you can set the optional parameter rootID/prefix to any prefix which is used instead. Is this case it has to be a string.
If rootID/prefix is an integer and unequal to 0 the link is constructed from all the names starting at the object with the id rootID/prefix separated by a slash relative to the current object. If for example the above document 'internet_movie' is located at 'a-b-c-internet_movie' with '-' being the seperator between hierachy 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 hierachy onto the file system.
This function will only work for pure text documents. It will not open a special data connection and therefore blocks the control connection during the transfer.
See also hw_PipeDocument(), hw_FreeDocument(), hw_DocumentBodyTag(), hw_DocumentSize(), hw_OutputDocument().
array hw_getobjectbyquery
(int connection, string query, int
max_hits)
Searches for objects on the whole server and returns an array of object ids. The maximum number of matches is limited to max_hits. If max_hits is set to -1 the maximum number of matches is unlimited.
The query will only work with indexed attributes.
See also hw_GetObjectByQueryObj().
array hw_getobjectbyqueryobj
(int connection, string query,
int max_hits)
Searches for objects on the whole server and returns an array of object records. The maximum number of matches is limited to max_hits. If max_hits is set to -1 the maximum number of matches is unlimited.
The query will only work with indexed attributes.
See also hw_GetObjectByQuery().
array hw_getobjectbyquerycoll
(int connection, int objectID,
string query, int max_hits)
Searches for objects in collection with ID objectID and returns an array of object ids. The maximum number of matches is limited to max_hits. If max_hits is set to -1 the maximum number of matches is unlimited.
The query will only work with indexed attributes.
See also hw_GetObjectByQueryCollObj().
array hw_getobjectbyquerycollobj
(int connection, int
objectID, string query, int max_hits)
Searches for objects in collection with ID objectID and returns an array of object records. The maximum number of matches is limited to max_hits. If max_hits is set to -1 the maximum number of matches is unlimited.
The query will only work with indexed attributes.
See also hw_GetObjectByQueryColl().
array hw_getchilddoccoll
(int connection, int
objectID)
Returns array of object ids for child documents of a collection.
See also hw_GetChildren(), hw_GetChildColl().
array hw_getchilddoccollobj
(int connection, int
objectID)
Returns an array of object records for child documents of a collection.
See also hw_ChildrenObj(), hw_GetChildCollObj().
array hw_getanchors
(int connection, int objectID)
Returns an array of object ids with anchors of the document with object ID objectID.
array hw_getanchorsobj
(int connection, int objectID)
Returns an array of object records with anchors of the document with object ID objectID.
int hw_mv
(int
connection, array object id array, int source id, int destination id)
Moves the objects with object ids as specified in the second parameter from the collection with id source id to the collection with the id destination id. If the destination id is 0 the objects will be unlinked from the source collection. If this is the last instance of that object it will be deleted. If you want to delete all instances at once, use hw_deleteobject().
The value return is the number of moved objects.
See also hw_cp(), hw_deleteobject().
int hw_identify
(string username, string password)
Identifies as user with username and password. Identification is only valid for the current session. I do not thing this function will be needed very often. In most cases it will be easier to identify with the opening of the connection.
See also hw_Connect().
array hw_incollections
(int connection, array object_id_array, array collection_id_array, int
return_collections)
Checks whether a set of objects (documents or collections) specified by the object_id_array is part of the collections listed in collection_id_array. When the fourth parameter return_collections is 0, the subset of object ids that is part of the collections (i.e., the documents or collections that are children of one or more collections of collection ids or their subcollections, recursively) is returned as an array. When the fourth parameter is 1, however, the set of collections that have one or more objects of this subset as children are returned as an array. This option allows a client to, e.g., highlight the part of the collection hierarchy that contains the matches of a previous query, in a graphical overview.
string hw_info
(int
connection)
Returns information about the current connection. The returned string has the following format: <Serverstring>, <Host>, <Port>, <Username>, <Port of Client>, <Byte swapping>
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.
int hw_insdoc
(int
connection, int parentID, string object_record, string text)
Inserts a new document with attributes as in object_record into collection with object ID parentID. This function inserts either an object record only or an object record and a pure ascii text in text if text is given. If you want to insert a general document of any kind use hw_insertdocument() instead.
See also hw_InsertDocument(), hw_InsColl().
int hw_insertdocument
(int connection, int parent_id, int hw_document)
Uploads a document into the collection with parent_id. The document has to be created before with hw_NewDocument(). Make sure that the object record of the new document contains at least the attributes: Type, DocumentType, Title and Name. Possibly you also want to set the MimeType. The functions returns the object id of the new document or false.
See also hw_PipeDocument().
int hw_insertobject
(int connection, string object rec, string parameter)
Inserts an object into the server. The object can be any valid hyperwave object. See the HG-CSP documentation for a detailed information on how the parameters have to be.
Note: If you want to insert an Anchor, the attribute Position has always been set either to a start/end value or to 'invisible'. Invisible positions are needed if the annotation has no correspondig link in the annotation text.
See also hw_PipeDocument(), hw_InsertDocument(), hw_InsDoc(), hw_InsColl().
int hw_mapid
(int
connection, int server id, int object id)
Maps a global object id on any hyperwave server, even those you did not connect to with hw_connect(), onto a virtual object id. This virtual object id can then be used as any other object id, e.g. to obtain the object record with hw_getobject(). The server id is the first part of the global object id (GOid) of the object which is actually the IP number as an integer.
Note: In order to use this function you will have to set the F_DISTRIBUTED flag, which can currently only be set at compile time in hg_comm.c. It is not set by default. Read the comment at the beginning of hg_comm.c
int hw_modifyobject
(int connection, int object_to_change, array remove, array add, int
mode)
This command allows to remove, add, or modify individual attributes of an object record. The object is specified by the Object ID object_to_change. The first array remove is a list of attributes to remove. The second array add is a list of attributes to add. In order to modify an attribute one will have to remove the old one and add a new one. hw_modifyobject() will always remove the attributes before it adds attributes unless the value of the attribute to remove is not a string or array.
The last parameter determines if the modification is performed recursively. 1 means recurive modification. If some of the objects cannot be modified they will be skiped without notice. hw_error() may not indicate an error though some of the objects could not be modified.
The keys of both arrays are the attributes name. The value of each array element can either be an array, a string or anything else. If it is an array each attribute value is constructed by the key of each element plus a colon and the value of each element. If it is a string it is taken as the attribute value. An empty string will result in a complete removal of that attribute. If the value is neither a string nor an array but something else, e.g. an integer, no operation at all will be performed on the attribute. This is neccessary if you want to 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
|
Example 2. adding a completely new attribute
|
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
|
Example 4. modifying Title attribute
|
Example 5. removing attribute
|
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 suround this function by calls to hw_getandlock() and hw_unlock(). hw_modifyobject() does this internally.
Returns TRUE if no error occurs otherwise FALSE.
int hw_new_document
(string object_record, string document_data, int document_size)
Returns a new Hyperwave document with document data set to document_data and object record set to object_record. The length of the document_data has to passed in document_sizeThis function does not insert the document into the Hyperwave server.
See also hw_FreeDocument(), hw_DocumentSize(), hw_DocumentBodyTag(), hw_OutputDocument(), hw_InsertDocument().
array hw_objrec2array
(string object_record)
Converts an object_record into an object array. The keys of the resulting array are the attributes names. Multiple 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. Currently only the attributes 'Title', 'Description' and 'Keyword' are treated properly. Other multiple attributes form an index array. Currently only the attribute 'Group' is handled properly.
See also hw_array2objrec().
int hw_pconnect
(string host, int port, string username, string password)
Returns a connection index on success, or false if the connection could not be made. Opens a persistent connection to a Hyperwave server. Each of the arguments should be a quoted string, except for the port number. The username and password arguments are optional and can be left out. In such a case no identification with the server will be done. It is similar to identify as user anonymous. This function returns a connection index that is needed by other Hyperwave functions. You can have multiple persistent connections open at once.
See also hw_Connect().
int hw_pipedocument
(int connection, int objectID)
Returns the Hyperwave document with object ID objectID. If the document has anchors which can be inserted, they will have been inserted already. The document will be transfered via a special data connection which does not block the control connection.
See also hw_GetText() for more on link insertion, hw_FreeDocument(), hw_DocumentSize(), hw_DocumentBodyTag(), hw_OutputDocument().
int hw_root
()
Returns the object ID of the hyperroot collection. Currently this is always 0. The child collection of the hyperroot is the root collection of the connected server.
int hw_unlock
(int
connection, int objectID)
Unlocks a document, so other users regain access.
See also hw_GetAndLock().
int hw_who
(int
connection)
Returns an array of users currently logged into the Hyperwave server. Each entry in this array is an array itself containing the elements id, name, system, onSinceDate, onSinceTime, TotalTime and self. 'self' is 1 if this entry belongs to the user who initianted the request.
To get these functions to work, you have to compile PHP with --with-icap. That requires the icap library to be installed. Grab the latest version from http://icap.chek.com/ and compile and install it.
stream icap_open
(string calendar, string username, string password, string options)
Returns an ICAP stream on success, false on error.
icap_open() opens up an ICAP connection to the specified calendar store. If the optional options is specified, passes the options to that mailbox also.
int icap_fetch_event
(int stream_id, int event_id [, int options])
Icap_fetch_event() fetches an event from the calendar stream specified by event_id.
Returns an event object consisting of:
int id - ID of that event.
int public - TRUE if the event if public, FALSE if it is private.
string category - Category string of the event.
string title - Title string of the event.
string description - Description string of the event.
int alarm - number of minutes before the event to send an alarm/reminder.
object start - Object containing a datetime entry.
object end - Object containing a datetime entry.
int year - year
int month - month
int mday - day of month
int hour - hour
int min - minutes
int sec - seconds
array icap_list_events
(int stream_id, int begin_date [, int end_date])
Returns an array of event ID's that are between the two given datetimes.
Icap_list_events() function takes in a beginning datetime and an end datetime for a calendar stream. An array of event id's that are between the given datetimes are returned.
All datetime entries consist of an object that contains:
int year - year
int month - month
int mday - day of month
int hour - hour
int min - minutes
int sec - seconds
string icap_store_event
(int stream_id, object
event)
Icap_store_event() Stores an event into an ICAP calendar. An event object consists of:
int public - 1 if public, 0 if private;
string caegory - Category string of the event.
string title - Title string of the event.
string description - Description string of the event.
int alarm - Number of minutes before the event to sned out an alarm.
datetime start - datetime object of the start of the event.
datetime end - datetime object of the end of the event.
All datetime entries consist of an object that contains:
int year - year
int month - month
int mday - day of month
int hour - hour
int min - minutes
int sec - seconds
Returns true on success and false on error.
string icap_delete_event
(int sream_id, int uid)
Icap_delete_event() deletes the calendar event specified by the uid.
Returns true.
string icap_snooze
(int stream_id, int uid)
Icap_snooze() turns on an alarm for a calendar event specified by the uid.
Returns true.
(PHP4 >= 4.0b4)
icap_list_alarms -- Return a list of events that has an alarm triggered at the given datetimeint icap_list_alarms
(int stream_id, array date, array time)
Returns an array of event ID's that has an alarm going off at the given datetime.
Icap_list_alarms() function takes in a datetime for a calendar stream. An array of event id's that has an alarm should be going off at the datetime are returned.
All datetime entries consist of an object that contains:
int year - year
int month - month
int mday - day of month
int hour - hour
int min - minutes
int sec - seconds
You can use the image functions in PHP to get the size of JPEG, GIF, PNG, and SWF images, and if you have the GD library (available at http://www.boutell.com/gd/) you will also be able to create and manipulate images.
The format of images you are able to manipulate depend on the version of gd you install, and any other libraries gd might need to access those image formats. Versions of gd older than gd-1.6 support gif format images, and do not support png, where versions greater than gd-1.6 support png, not gif.
In order to read and write images in jpeg format, you will need to obtain and install jpeg-6b (available at ftp://ftp.uu.net/graphics/jpeg/), and then recompile gd to make use of jpeg-6b. You will also have to compile PHP with --with-jpeg-dir=/path/to/jpeg-6b.
To add support for Type 1 fonts, you can install t1lib (available at ftp://ftp.neuroinformatik.ruhr-uni-bochum.de/pub/software/t1lib/), and then add --with-t1lib[=dir].
array getimagesize
(string filename [, array imageinfo])
The GetImageSize() function will determine the size of any GIF, JPG, PNG or SWF 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.
Returns an array with 4 elements. Index 0 contains the width of the image in pixels. Index 1 contains the height. Index 2 a flag indicating the type of the image. 1 = GIF, 2 = JPG, 3 = PNG, 4 = SWF. Index 3 is a text string with the correct "height=xxx width=xxx" string that can be used directly in an IMG tag.
Example 1. GetImageSize
|
The optional imageinfo parameter allows you to extract some extended information from the image file. Currently this will return the diffrent JPG APP markers in an associative Array. Some Programs use these APP markers to embedd text information in images. A very common one in to embed IPTC http://www.xe.net/iptc/ information in the APP13 marker. You can use the iptcparse() function to parse the binary APP13 marker into something readable.
Example 2. GetImageSize returning IPTC
|
Note: This function does not require the GD image library.
int imagearc
(int im,
int cx, int cy, int w, int h, int s, int e, int col)
ImageArc() draws a partial ellipse centered at cx, cy (top left is 0, 0) in the image represented by im. W and h specifies the ellipse's width and height respectively while the start and end points are specified in degrees indicated by the s and e. arguments.
int imagechar
(int im,
int font, int x, int y, string c, int col)
ImageChar() draws the first character of c in the image identified by id with its upper-left at x,y (top left is 0, 0) with the color col. If font is 1, 2, 3, 4 or 5, a built-in font is used (with higher numbers corresponding to larger fonts).
See also imageloadfont().
int imagecharup
(int
im, int font, int x, int y, string c, int col)
ImageCharUp() draws the character c vertically in the image identified by im at coordinates x, y (top left is 0, 0) with the color col. If font is 1, 2, 3, 4 or 5, a built-in font is used.
See also imageloadfont().
int imagecolorallocate
(int im, int red, int green, int blue)
ImageColorAllocate() returns a color identifier representing the color composed of the given RGB components. The im argument is the return from the imagecreate() function. ImageColorAllocate() must be called to create each color that is to be used in the image represented by im.
$white = ImageColorAllocate ($im, 255, 255, 255); $black = ImageColorAllocate ($im, 0, 0, 0); |
int imagecolordeallocate
(int im, int index)
The ImageColorDeAllocate() function de-allocates a color previously allocated with the ImageColorAllocate() function.
$white = ImageColorAllocate($im, 255, 255, 255); ImageColorDeAllocate($im, $white); |
int imagecolorat
(int
im, int x, int y)
Returns the index of the color of the pixel at the specified location in the image.
See also imagecolorset() and imagecolorsforindex().
int imagecolorclosest
(int im, 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.
See also imagecolorexact().
int imagecolorexact
(int im, int red, int green, int blue)
Returns the index of the specified color in the palette of the image.
If the color does not exist in the image's palette, -1 is returned.
See also imagecolorclosest().
(PHP3 >= 3.0.2, PHP4 )
ImageColorResolve -- Get the index of the specified color or its closest possible alternativeint imagecolorresolve
(int im, 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.
See also imagecolorclosest().
int imagegammacorrect
(int im, double inputgamma, double outputgamma)
The ImageGammaCorrect() function applies gamma correction to a gd image stream (im) given an input gamma, the parameter inputgamma and an output gamma, the parameter outputgamma.
bool imagecolorset
(int im, int index, int red, int green, int blue)
This sets the specified index in the palette to the specified color. This is useful for creating flood-fill-like effects in paletted images without the overhead of performing the actual flood-fill.
See also imagecolorat().
array imagecolorsforindex
(int im, int index)
This returns an associative array with red, green, and blue keys that contain the appropriate values for the specified color index.
See also imagecolorat() and imagecolorexact().
int imagecolorstotal
(int im)
This returns the number of colors in the specified image's palette.
See also imagecolorat() and imagecolorsforindex().
int imagecolortransparent
(int im [, int col])
ImageColorTransparent() sets the transparent color in the im image to col. Im is the image identifier returned by ImageCreate() and col is a color identifier returned by ImageColorAllocate().
The identifier of the new (or current, if none is specified) transparent color is returned.
int ImageCopy
(int
dst_im, int 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.
int imagecopyresized
(int dst_im, int src_im, int dstX, int dstY, int srcX, int srcY, int dstW, int
dstH, int srcW, int srcH)
ImageCopyResized() copies a rectangular portion of one image to another image. Dst_im is the destination image, src_im is the source image identifier. If the source and destination coordinates and width and heights differ, appropriate stretching or shrinking of the image fragment will be performed. The coordinates refer to the upper left corner. This function can be used to copy regions within the same image (if dst_im is the same as src_im) but if the regions overlap the results will be unpredictable.
int imagecreate
(int
x_size, int y_size)
ImageCreate() returns an image identifier representing a blank image of size x_size by y_size.
Example 1. Creating a new GD image stream and outputting an image.
|
int imagecreatefromgif
(string filename)
ImageCreateFromGif() returns an image identifier representing the image obtained from the given filename.
ImageCreateFromGif() returns an empty string on failure. It also outputs an error message, which unfortunately displays as a broken link in a browser. To ease debugging the following example will produce an error GIF:
Example 1. Example to handle an error during creation (courtesy vic@zymsys.com)
|
Note: Since all GIF support was removed from the GD library in version 1.6, this function is not available if you are using that version of the GD library.
int imagecreatefromjpeg
(string filename)
ImageCreateFromJPEG() returns an image identifier representing the image obtained from the given filename.
ImagecreateFromJPEG() returns an empty string on failure. It also outputs an error message, which unfortunately displays as a broken link in a browser. To ease debugging the following example will produce an error JPEG:
Example 1. Example to handle an error during creation (courtesy vic@zymsys.com )
|
int imagecreatefrompng
(string filename)
ImageCreateFromPNG() returns an image identifier representing the image obtained from the given filename.
ImageCreateFromPNG() returns an empty string on failure. It also outputs an error message, which unfortunately displays as a broken link in a browser. To ease debugging the following example will produce an error PNG:
Example 1. Example to handle an error during creation (courtesy vic@zymsys.com)
|
int imagedashedline
(int im, int x1, int y1, int x2, int y2, int col)
ImageDashedLine() draws a dashed line from x1, y1 to x2, y2 (top left is 0, 0) in image im of color col.
See also ImageLine().
int imagedestroy
(int
im)
ImageDestroy() frees any memory associated with image im. Im is the image identifier returned by the ImageCreate() function.
int imagefill
(int im,
int x, int y, int col)
ImageFill() performs a flood fill starting at coordinate x, y (top left is 0, 0) with color col in the image im.
int imagefilledpolygon
(int im, array points, int num_points, int col)
ImageFilledPolygon() creates a filled polygon in image im. Points is a PHP array containing the polygon's vertices, ie. points[0] = x0, points[1] = y0, points[2] = x1, points[3] = y1, etc. Num_points is the total number of vertices.
int imagefilledrectangle
(int im, int x1, int y1, int x2,
int y2, int col)
ImageFilledRectangle() creates a filled rectangle of color col() in image im starting at upper left coordinates x1, y1 and ending at bottom right coordinates x2, y2. 0, 0 is the top left corner of the image.
int imagefilltoborder
(int im, int x, int y, int border, int col)
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 col.
int imagefontheight
(int font)
Returns the pixel height of a character in the specified font.
See also ImageFontWidth() and ImageLoadFont().
int imagefontwidth
(int font)
Returns the pixel width of a character in font.
See also ImageFontHeight() and ImageLoadFont().
int imagegif
(int im
[, string filename])
ImageGIF() creates the GIF file in filename from the image im. The im argument is the return from the imagecreate() 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.
The filename argument is optional, and if left off, the raw image stream will be output directly. By sending an image/gif content-type using header(), you can create a PHP script that outputs GIF images directly.
Note: Since all GIF support was removed from the GD library in version 1.6, this function is not available if you are using that version of the GD library.
int imagepng
(int im
[, string filename])
The ImagePng() outputs a GD image stream (im) in PNG format to standard output (usually the browser) or, if a filename is given by the filename it outputs the image to the file.
<?php $im = ImageCreateFromPng("test.png"); ImagePng($im); ?> |
int imagejpeg
(int im
[, string filename [, int quality]])
ImageJPEG() creates the JPEG file in filename from the image im. The im argument is the return from the ImageCreate() function.
The filename argument is optional, and if left off, the raw image stream will be output directly. To skip the filename argument in order to provide a quality argument just use an empty string (''). By sending an image/jpeg content-type using header(), you can create a PHP script that outputs JPEG images directly.
Note: JPEG support is only available in PHP if PHP was compiled against GD-1.8 or later.
int imageinterlace
(int im [, int interlace])
ImageInterlace() turns the interlace bit on or off. If interlace is 1 the im image will be interlaced, and if interlace is 0 the interlace bit is turned off.
This functions returns whether the interlace bit is set for the image.
int imageline
(int im,
int x1, int y1, int x2, int y2, int col)
ImageLine() draws a line from x1, y1 to x2, y2 (top left is 0, 0) in image im of color col.
See also ImageCreate() and ImageColorAllocate().
int imageloadfont
(string file)
ImageLoadFont() loads a user-defined bitmap font and returns an identifier for the font (that is always greater than 5, so it will not conflict with the built-in fonts).
The font file format is currently binary and architecture dependent. This means you should generate the font files on the same type of CPU as the machine you are running PHP on.
Table 1. Font file format
byte position | C data type | description |
---|---|---|
byte 0-3 | int | number of characters in the font |
byte 4-7 | int | value of first character in the font (often 32 for space) |
byte 8-11 | int | pixel width of each character |
byte 12-15 | int | pixel height of each character |
byte 16- | char | array with character data, one byte per pixel in each character, for a total of (nchars*width*height) bytes. |
See also ImageFontWidth() and ImageFontHeight().
int imagepolygon
(int
im, array points, int num_points, int col)
ImagePolygon() creates a polygon in image id. Points is a PHP array containing the polygon's vertices, ie. points[0] = x0, points[1] = y0, points[2] = x1, points[3] = y1, etc. Num_points is the total number of vertices.
See also imagecreate().
(PHP3 >= 3.0.9, PHP4 >= 4.0RC1)
ImagePSBBox -- Give the bounding box of a text rectangle using PostScript Type1 fontsarray imagepsbbox
(string text, int font, int size [, int space [, int tightness [, float
angle]]])
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.
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.
Angle is in degrees.
Parameters space and tightness are expressed in character space units, where 1 unit is 1/1000th of an em-square.
Parameters space, tightness, and angle are optional.
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.
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 |
See also imagepstext().
int imagepsencodefont
(string encodingfile)
Loads a character encoding vector from 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. The exact format of this file is described in T1libs documentation. T1lib comes with two ready-to-use files, IsoLatin1.enc and IsoLatin2.enc.
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.
int imagepsloadfont
(string filename)
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 and prints a message describing what went wrong.
See also ImagePSFreeFont().
bool imagepsextendfont
(int font_index, double 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.
bool imagepsslantfont
(int font_index, double slant)
Slant a font given by the font_index parameter with a slant of the value of the slant parameter.
(PHP3 >= 3.0.9, PHP4 >= 4.0RC1)
ImagePSText -- To draw a text string over an image using PostScript Type1 fontsarray imagepstext
(int
image, string text, int font, int size, int foreground, int background, int x,
int y [, int space [, int tightness [, float angle [, int
antialias_steps]]]])
Size is expressed in pixels.
Foreground is the color in which the text will be painted. Background is 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.
The coordinates given by x, y will define the origin (or reference point) of the first character (roughly the lower-left corner of the character). This is different from the ImageString(), where x, y define the upper-right corner of the first character. Refer to PostScipt documentation about fonts and their measuring system if you have trouble understanding how this works.
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.
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.
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.
Parameters space and tightness are expressed in character space units, where 1 unit is 1/1000th of an em-square.
Parameters space, tightness, angle and antialias are optional.
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 |
See also imagepsbbox().
int imagerectangle
(int im, int x1, int y1, int x2, int y2, int col)
ImageRectangle() creates a rectangle of color col in image im starting at upper left coordinate x1, y1 and ending at bottom right coordinate x2, y2. 0, 0 is the top left corner of the image.
int imagesetpixel
(int
im, int x, int y, int col)
ImageSetPixel() draws a pixel at x, y (top left is 0, 0) in image im of color col.
See also ImageCreate() and ImageColorAllocate().
int imagestring
(int
im, int font, int x, int y, string s, int col)
ImageString() draws the string s in the image identified by im at coordinates x, y (top left is 0, 0) in color col. If font is 1, 2, 3, 4 or 5, a built-in font is used.
See also ImageLoadFont().
int imagestringup
(int
im, int font, int x, int y, string s, int col)
ImageStringUp() draws the string s vertically in the image identified by im at coordinates x, y (top left is 0, 0) in color col. If font is 1, 2, 3, 4 or 5, a built-in font is used.
See also ImageLoadFont().
int imagesx
(int
im)
ImageSX() returns the width of the image identified by im.
See also ImageCreate() and ImageSY().
int imagesy
(int
im)
ImageSY() returns the height of the image identified by im.
See also ImageCreate() and ImageSX().
array imagettfbbox
(int size, int angle, string fontfile, string text)
This function calculates and returns the bounding box in pixels for a TrueType text.
The string to be measured.
The font size.
The name of the TrueType font file. (Can also be an URL.)
Angle in degrees in which text will be measured.
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 |
This function requires both the GD library and the FreeType library.
See also ImageTTFText().
array imagettftext
(int im, int size, int angle, int x, int y, int col, string fontfile, string
text)
ImageTTFText() draws the string text in the image identified by im, starting at coordinates x, y (top left is 0, 0), at an angle of angle in color col, using the TrueType font file identified by fontfile.
The coordinates given by x, 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, y define the upper-right corner of the first character.
Angle is in degrees, with 0 degrees being left-to-right reading text (3 o'clock direction), and higher values representing a counter-clockwise rotation. (i.e., a value of 90 would result in bottom-to-top reading text).
Fontfile is the path to the TrueType font you wish to use.
Text is the text string which may include UTF-8 character sequences (of the form: {) to access characters in a font beyond the first 255.
Col is the color index. Using the negative of a color index has the effect of turning off antialiasing.
ImageTTFText() returns an array with 8 elements representing four points making the bounding box of the text. The order of the points is upper left, upper right, lower right, lower 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 horizontallty.
This example script will produce a black GIF 400x30 pixels, with the words "Testing..." in white in the font Arial.
Example 1. ImageTTFText
|
This function requires both the GD library and the FreeType library.
See also ImageTTFBBox().
int imagetypes
(void);
This function 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. To check for PNG support, for example, do this:
Example 1. ImageTypes
|
array read_exif_data
(string filename)
The read_exif_data() function reads the EXIF headers from a JPEG image file. It returns an associative array where the indexes are the Exif header names and the values are the values associated with those Exif headers. Exif headers tend to be present in JPEG 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.
Example 1. read_exif_data
|
Note: This function is only available in PHP4 compiled using --enable-exif
This function does not require the GD image library.
To get these functions to work, you have to compile PHP with --with-imap. That requires the c-client library to be installed. Grab the latest version from ftp://ftp.cac.washington.edu/imap/ and compile it. Then copy c-client/c-client.a to /usr/local/lib/libc-client.a or some other directory on your link path and copy c-client/rfc822.h, mail.h and linkage.h to /usr/local/include or some other directory in your include path.
Note that these functions are not limited to the IMAP protocol, despite their name. The underlying c-client library also supports NNTP, POP3 and local mailbox access methods.
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:
RFC821: Simple Mail Transfer Protocol (SMTP).
RFC822: 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).
int imap_append
(int
imap_stream, string mbox, string message [, string flags])
Returns true on sucess, false on error.
imap_append() appends a string message to the specified mailbox mbox. If the optional flags is specified, writes the flags to that mailbox also.
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.
Example 1. imap_append() example
|
string imap_base64
(string text)
imap_base64() function decodes BASE-64 encoded text (see RFC2045, Section 6.8). The decoded message is returned as a string.
See also imap_binary().
string imap_body
(int
imap_stream, int msg_number [, int flags])
imap_body() returns the body of the message, numbered msg_number in the current mailbox. The optional flags are a bit mask with one or more of the following:
FT_UID - The msgno 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.
object imap_check
(int
imap_stream)
Returns information about the current mailbox. Returns FALSE on failure.
The imap_check() function checks the current mailbox status on the server and returns the information in an object with following properties:
Date - last change of mailbox contents
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
int imap_close
(int
imap_stream [, int flags])
Close the imap stream. Takes an optional flag CL_EXPUNGE, which will silently expunge the mailbox before closing, removing all messages marked for deletion.
int imap_createmailbox
(int imap_stream, string mbox)
imap_createmailbox() creates a new mailbox specified by mbox. Names containing international characters should be encoded by imap_utf7_encode()
Returns true on success and false on error.
See also imap_renamemailbox(), imap_deletemailbox() and imap_open() for the format of mbox names.
Example 1. imap_createmailbox() example
|
int imap_delete
(int
imap_stream, int msg_number [, int flags])
Returns true.
imap_delete() function marks message pointed by msg_number for deletion. The optional flags parameter only has a single option, FT_UID, which tells the function to treat the msg_number argument as a UID. 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.
Example 1. Imap_delete() Beispiel
|
int imap_deletemailbox
(int imap_stream, string mbox)
imap_deletemailbox() deletes the specified mailbox (see imap_open() for the format of mbox names).
Returns true on success and false on error.
See also imap_createmailbox(), imap_renamemailbox(), and imap_open() for the format of mbox.
int imap_expunge
(int
imap_stream)
imap_expunge() deletes all the messages marked for deletion by imap_delete(), imap_mail_move(), or imap_setflag_full().
Returns true.
string imap_fetchbody
(int imap_stream, int msg_number, string part_number [, flags flags])
This function causes a fetch of a particular section of the body of the specified messages as a text string and returns that text string. The section specification is a string of integers delimited by period which index into a body part list as per the IMAP4 specification. Body parts are not decoded by this function.
The options for imap_fetchbody() is 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, without any attempt to canonicalize CRLF.
object imap_fetchstructure
(int imap_stream, int msg_number [, int flags])
This function fetches all the structured information for a given message. The optional flags parameter only has a single option, FT_UID, which tells the function to treat the msg_number argument as a UID. The returned object includes the envelope, internal date, size, flags and body structure along with a similar object for each mime attachement. The structure of the returned objects is as follows:
Table 1. Returned Objects for imap_fetchstructure()
type | Primary body type |
encoding | Body transfer encoding |
ifsubtype | True if there is a subtype string |
subtype | MIME subtype |
ifdescription | True if there is a description string |
description | Content description string |
ifid | True if there is an identification string |
id | Identification string |
lines | Number of lines |
bytes | Number of bytes |
ifdisposition | True if there is a disposition string |
disposition | Disposition string |
ifdparameters | True if the dparameters array exists |
dparameters | Disposition parameter array |
ifparameters | True if the parameters array exists |
parameters | MIME parameters array |
parts | Array of objects describing each message part |
dparameters is an array of objects where each object has an "attribute" and a "value" property.
Parameter is an array of objects where each object has an "attributte" and a "value" property.
Parts is an array of objects identical in structure to the top-level object, with the limitation that it cannot contain further 'parts' objects.
Table 2. Primary body type
0 | text |
1 | multipart |
2 | message |
3 | application |
4 | audio |
5 | image |
6 | video |
7 | other |
Table 3. Transfer encodings
0 | 7BIT |
1 | 8BIT |
2 | BINARY |
3 | BASE64 |
4 | QUOTED-PRINTABLE |
5 | OTHER |
object imap_header
(int imap_stream, int msg_number [, int fromlength [, int subjectlength [,
string defaulthost]]])
This function returns an object of various header elements.
remail, date, Date, subject, Subject, in_reply_to, message_id,
newsgroups, followup_to, references
message flags:
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
Answered -'A' if answered,
' ' if unanswered
Deleted - 'D' if deleted,
' ' if not deleted
Draft - 'X' if draft,
' ' if not draft
Flagged - 'F' if flagged,
' ' if not flagged
NOTE that the Recent/Unseen behavior is a little odd. If you want to
know if a message is Unseen, you must check for
Unseen == 'U' || Recent == 'N'
toaddress (full to: line, up to 1024 characters)
to[] (returns an array of objects from the To line, containing):
personal
adl
mailbox
host
fromaddress (full from: line, up to 1024 characters)
from[] (returns an array of objects from the From line, containing):
personal
adl
mailbox
host
ccaddress (full cc: line, up to 1024 characters)
cc[] (returns an array of objects from the Cc line, containing):
personal
adl
mailbox
host
bccaddress (full bcc line, up to 1024 characters)
bcc[] (returns an array of objects from the Bcc line, containing):
personal
adl
mailbox
host
reply_toaddress (full reply_to: line, up to 1024 characters)
reply_to[] (returns an array of objects from the Reply_to line,
containing):
personal
adl
mailbox
host
senderaddress (full sender: line, up to 1024 characters)
sender[] (returns an array of objects from the sender line, containing):
personal
adl
mailbox
host
return_path (full return-path: line, up to 1024 characters)
return_path[] (returns an array of objects from the return_path line,
containing):
personal
adl
mailbox
host
udate (mail message date in unix time)
fetchfrom (from line formatted to fit fromlength
characters)
fetchsubject (subject line formatted to fit subjectlength characters)
object imap_rfc822_parse_headers
(string headers [, string
defaulthost])
This function returns an object of various header elements, similar to imap_header(), except without the flags and other elements that come from the IMAP server.
array imap_headers
(int imap_stream)
Returns an array of string formatted with header info. One element per mail message.
array imap_listmailbox
(int imap_stream, string ref, string pattern)
Returns an array containing the names of the mailboxes. See imap_getmailboxes() for a description of ref and pattern.
Example 1. imap_getmailboxes() example
|
(PHP3 >= 3.0.12, PHP4 >= 4.0b4)
imap_getmailboxes -- Read the list of mailboxes, returning detailed information on each onearray imap_getmailboxes
(int imap_stream, string ref, string
pattern)
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.
Mailbox names containing international Characters outside the printable ASCII range will be encoded and may be decoded by imap_utf7_decode().
ref should normally be just the server specification as described in imap_open(), and pattern specifies where in the mailbox hierarchy to start searching. If you want all mailboxes, pass '*' for pattern.
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.
Example 1. imap_getmailboxes() example
|
array imap_listsubscribed
(int imap_stream, string ref,
string pattern)
Returns an array of all the mailboxes that you have subscribed. This is almost identical to imap_listmailbox(), but will only return mailboxes the user you logged in as has subscribed.
array imap_getsubscribed
(int imap_stream, string ref,
string pattern)
This function is identical to imap_getmailboxes(), except that it only returns mailboxes that the user is subscribed to.
int imap_mail_copy
(int imap_stream, string msglist, string mbox [, int flags])
Returns true on success and false on error.
Copies mail messages specified by msglist to specified mailbox. msglist is a range not just message numbers (as described in RFC2060).
Flags is a bitmask of one or more of
CP_UID - the sequence numbers contain UIDS
CP_MOVE - Delete the messages from the current mailbox after copying
int imap_mail_move
(int imap_stream, string msglist, string mbox [, int flags])
Moves mail messages specified by msglist to specified mailbox. msglist is a range not just message numbers (as described in RFC2060).
Flags is a bitmask and may contain the single option
CP_UID - the sequence numbers contain UIDS
Returns true on success and false on error.
int imap_num_msg
(int
imap_stream)
Return the number of messages in the current mailbox.
int imap_num_recent
(int imap_stream)
Returns the number of recent messages in the current mailbox.
int imap_open
(string
mailbox, string username, string password [, int flags])
Returns an IMAP stream on success and false on error. This function can also be used to open streams to POP3 and NNTP servers, but some functions and features are not available on IMAP servers.
A mailbox name consists of a server part and a mailbox path on this server. The special name INBOX stands for the current users personal mailbox. The server part, which is enclosed in '{' and '}', consists of the servers name or ip address, a protocol secification (beginning with '/') and an optional port specifier beginnung with ':'. The server part is mandatory in all mailbox parameters. Mailbos names that contain international characters besides those in the printable ASCII space have to be encoded with imap_utf7_encode().
The options are a bit mask with one or more of the following:
OP_READONLY - Open mailbox read-only
OP_ANONYMOUS - Dont use or update a .newsrc for news (NNTP only)
OP_HALFOPEN - For IMAP and NNTP names, open a connection but dont open a mailbox
CL_EXPUNGE - Expunge mailbox automatically upon mailbox close
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"); |
$mbox = imap_open ("{localhost/pop3:110}INBOX", "user_id", "password"); |
$nntp = imap_open ("{localhost/nntp:119}comp.test", "", ""); |
Example 1. imap_open() example
|
int imap_ping
(int
imap_stream)
Returns true if the stream is still alive, false otherwise.
imap_ping() function pings the stream to see it is 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. (As PHP scripts do not tend to run that long, i can hardly imagine that this function will be usefull to anyone.)
int imap_renamemailbox
(int 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).
Returns true on success and false on error.
See also imap_createmailbox(), imap_deletemailbox(), and imap_open() for the format of mbox.
int imap_reopen
(int
imap_stream, string mailbox [, string flags])
This function reopens the specified stream to a new mailbox on an IMAP or NNTP server.
The options are a bit mask with one or more of the following:
OP_READONLY - Open mailbox read-only
OP_ANONYMOUS - Dont use or update a .newsrc for news (NNTP only)
OP_HALFOPEN - For IMAP and NNTP names, open a connection but dont open a mailbox.
CL_EXPUNGE - Expunge mailbox automatically upon mailbox close (see also imap_delete() and imap_expunge())
Returns true on success and false on error.
int imap_subscribe
(int imap_stream, string mbox)
Subscribe to a new mailbox.
Returns true on success and false on error.
int imap_undelete
(int
imap_stream, int msg_number)
This function removes the deletion flag for a specified message, which is set by imap_delete() or imap_mail_move().
Returns true on success and false on error.
int imap_unsubscribe
(int imap_stream, string mbox)
Unsubscribe from a specified mailbox.
Returns true on success and false on error.
string imap_qprint
(string string)
Convert a quoted-printable string to an 8 bit string (according to RFC2045, section 6.7).
Returns an 8 bit (binary) string.
See also imap_8bit().
string imap_8bit
(string string)
Convert an 8bit string to a quoted-printable string (according to RFC2045, section 6.7).
Returns a quoted-printable string.
See also imap_qprint().
string imap_binary
(string string)
Convert an 8bit string to a base64 string (according to RFC2045, Section 6.8).
Returns a base64 string.
See also imap_base64().
(PHP3 , PHP4 )
imap_scanmailbox -- Read the list of mailboxes, takes a string to search for in the text of the mailboxarray imap_scanmailbox
(int imap_stream, string content)
Returns an array containing the names of the mailboxes that have string in the text of the mailbox. This function is simmilar to imap_listmailbox(), but it will additionally check for the presence of the string content inside the mailbox data.
object imap_mailboxmsginfo
(int imap_stream)
Returns information about the current mailbox. Returns FALSE on failure.
The imap_mailboxmsginfo() function 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. It returns the information in an object with following properties.
Table 1. Mailbox properties
Date | date of last change |
Driver | driver |
Mailbox | name of the mailbox |
Nmsgs | number of messages |
Recent | number of recent messages |
Unread | number of unread messages |
Deleted | number of deleted messages |
Size | mailbox size |
Example 1. imap_mailboxmsginfo() example
|
(PHP3 >= 3.0.2, PHP4 )
imap_rfc822_write_address -- Returns a properly formatted email address given the mailbox, host, and personal info.string imap_rfc822_write_address
(string mailbox, string
host, string personal)
Returns a properly formatted email address as defined in RFC822 given the mailbox, host, and personal info.
Example 1. imap_rfc822_write_address() example
|
array imap_rfc822_parse_adrlist
(string address, string
default_host)
This function parses the address string as defined in RFC822 and for each address, returns an array of objects. The objects properties are:
mailbox - the mailbox name (username)
host - the host name
personal - the personal name
adl - at domain source route
Example 1. imap_rfc822_parse_adrlist() example
|
string imap_setflag_full
(int stream, string sequence, string
flag, string options)
This function causes a store to add the specified flag to the flags set for the messages in the specified sequence.
The flags which you can set are "\\Seen", "\\Answered", "\\Flagged", "\\Deleted", "\\Draft", and "\\Recent" (as defined by RFC2060).
The options are a bit mask with one or more of the following:
ST_UID The sequence argument contains UIDs instead of
sequence numbers
Example 1. imap_setflag_full() example
|
string imap_clearflag_full
(int stream, string sequence, string flag, string options)
This function causes a store to delete the specified flag to the flags set for the messages in the specified sequence. The flags which you can unset are "\\Seen", "\\Answered", "\\Flagged", "\\Deleted", "\\Draft", and "\\Recent" (as defined by RFC2060).
The options are a bit mask with one or more of the following:
ST_UID The sequence argument contains UIDs instead of
sequence numbers
array imap_sort
(int
stream, int criteria, int reverse, int options)
Returns an array of message numbers sorted by the given parameters.
Reverse is 1 for reverse-sorting.
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
The flags are a bitmask of one or more of the following:
SE_UID Return UIDs instead of sequence numbers
SE_NOPREFETCH Don't prefetch searched messages.
string imap_fetchheader
(int imap_stream, int msgno, int
flags)
This function causes a fetch of the complete, unfiltered RFC822 format header of the specified message as a text string and returns that text string.
The 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)
(PHP3 >= 3.0.3, PHP4 )
imap_uid -- This function returns the UID for the given message sequence numberint imap_uid
(int
imap_stream, int msgno)
This function returns the UID for the given message sequence number. An UID is an 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().
(PHP3 >= 3.0.3, PHP4 )
imap_msgno -- This function returns the message sequence number for the given UIDint imap_msgno
(int
imap_stream, int uid)
This function returns the message sequence number for the given UID. It is the inverse of imap_uid().
(PHP3 >= 3.0.12, PHP4 >= 4.0b4)
imap_search -- This function returns an array of messages matching the given search criteriaarray imap_search
(int
imap_stream, string criteria, int flags)
This function performs a search on the mailbox currently opened in the given imap stream. criteria is a string, delimited by spaces, in which the following keywords are allowed. Any multi-word arguments (eg. FROM "joey smith") must be quoted.
ALL - return all messages matching the rest of the criteria
ANSWERED - match messages with the \\ANSWERED flag set
BCC "string" - match messages with "string" in the Bcc: field
BEFORE "date" - match messages with Date: before "date"
BODY "string" - match messages with "string" in the body of the message
CC "string" - match messages with "string" in the Cc: field
DELETED - match deleted messages
FLAGGED - match messages with the \\FLAGGED (sometimes referred to as Important or Urgent) flag set
FROM "string" - match messages with "string" in the From: field
KEYWORD "string" - match messages with "string" as a keyword
NEW - match new messages
OLD - match old messages
ON "date" - match messages with Date: matching "date"
RECENT - match messages with the \\RECENT flag set
SEEN - match messages that have been read (the \\SEEN flag is set)
SINCE "date" - match messages with Date: after "date"
SUBJECT "string" - match messages with "string" in the Subject:
TEXT "string" - match messages with text "string"
TO "string" - match messages with "string" in the To:
UNANSWERED - match messages that have not been answered
UNDELETED - match messages that are not deleted
UNFLAGGED - match messages that are not flagged
UNKEYWORD "string" - match messages that do not have the keyword "string"
UNSEEN - match messages which have not been read yet
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 uncomplete or inaccurate (see also RFC2060, section 6.4.4).
Valid values for flags are SE_UID, which causes the returned array to contain UIDs instead of messages sequence numbers.
(PHP3 >= 3.0.12, PHP4 >= 4.0b4)
imap_last_error -- This function returns the last IMAP error (if any) that occurred during this page requeststring imap_last_error
(void)
This function returns 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.
(PHP3 >= 3.0.12, PHP4 >= 4.0b4)
imap_errors -- This function returns all of the IMAP errors (if any) that have occurred during this page request or since the error stack was reset.array imap_errors
(void)
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. When imap_errors() is called, the error stack is subsequently cleared.
(PHP3 >= 3.0.12, PHP4 >= 4.0b4)
imap_alerts -- This function returns all IMAP alert messages (if any) that have occurred during this page request or since the alert stack was resetarray imap_alerts
(void)
This function returns an array of 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.
(PHP3 >= 3.0.4, PHP4 )
imap_status -- This function returns status information on a mailbox other than the current oneobject imap_status
(int imap_stream, string mailbox, int options)
This function returns an object containing status information. 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
status->flags is also set, which contains a bitmask which can be checked against any of the above constants.
Example 1. imap_status() example
|
string imap_utf7_decode
(string text)
Decodes modified UTF-7 text into 8bit data.
Returns the decoded 8bit data, or false if the input string was not valid modified UTF-7. This function is needed to decode mailbox names that contain international characters outside of the printable ASCII range. The modified UTF-7 encoding is defined in RFC 2060, section 5.1.3 (original UTF-7 was defned in RFC1642).
string imap_utf7_encode
(string data)
Converts 8bit data to modified UTF-7 text. This is needed to encode mailbox names that contain international characters outside of the printable ASCII range. The modified UTF-7 encoding is defined in RFC 2060, section 5.1.3 (original UTF-7 was defned in RFC1642).
Returns the modified UTF-7 text.
(PHP3 >= 3.0.4, PHP4 )
imap_fetch_overview -- Read an overview of the information in the headers of the given messagearray imap_fetch_overview
(int imap_stream, string sequence
[, int flags])
This function fetches mail headers for the given sequence and returns an overview of their contents. sequence will contain a sequence of message indices or UIDs, if flags contains FT_UID. The returned value is an array of objects describing one message header each:
subject - the messages subject
from - who sent it
date - when was it sent
message_id - Message-ID
references - is a reference to this message id
size - size in bytes
uid - UID the message has in the mailbox
msgno - message sequence number in the maibox
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
Example 1. imap_fetch_overview() example
|
array imap_header_decode
(string text)
imap_mime_header_decode() function decodes MIME message header extensions that are non ASCII text (see RFC2047) The decoded elements are returned in an array of objects, where each object has two properties, "charset" & "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".
Example 1. imap_mime_header_decode() example
|
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.
(PHP3 >= 3.0.5, PHP4 )
imap_mail_compose -- Create a MIME message based on given envelope and body sectionsstring imap_mail_compose
(array envelope, array
body)
Example 1. imap_mail_compose() example
|
The Informix driver for Informix (IDS) 7.x, SE 7.x, Universal Server (IUS) 9.x and IDS 2000 is implemented in "ifx.ec" and "php3_ifx.h" in the informix extension directory. IDS 7.x support is fairly complete, with full support for BYTE and TEXT columns. IUS 9.x support is partly finished: the new data types are there, but SLOB and CLOB support is still under construction.
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.
The configure script will autodetect the libraries and include directories, if you run "configure --with_informix=yes". You can overide this detection by specifying "IFX_LIBDIR", "IFX_LIBS" and "IFX_INCDIR" in the environment. The configure script will also try to detect your Informix server version. It will set the "HAVE_IFX_IUS" conditional compilation variable if your Informix version >= 9.00.
Runtime considerations: 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_LINBRARY_PATH or ld.so.conf/ldconfig).
Some notes on the use of BLOBs (TEXT and BYTE columns): BLOBs are normally addressed by BLOB identifiers. Select queries return a "blob id" for every BYTE and TEXT column. You can get at the contents with "string_var = ifx_get_blob($blob_id);" if you choose to get the BLOBs in memory (with : "ifx_blobinfile(0);"). If you prefer to receive the content of BLOB columns in a file, use "ifx_blobinfile(1);", and "ifx_get_blob($blob_id);" will get you the filename. Use normal file I/O to get at the blob contents.
For insert/update queries you must create these "blob id's" yourself with "ifx_create_blob();". You then plug the blob id's into an array, and replace the blob columns with a question mark (?) in the query string. For updates/inserts, you are responsible for setting the blob contents with ifx_update_blob().
The behaviour of BLOB columns can be altered by configuration variables that also can be set at runtime :
configuration variable : ifx.textasvarchar
configuration variable : ifx.byteasvarchar
runtime functions :
ifx_textasvarchar(0) : use blob id's for select queries with TEXT columns
ifx_byteasvarchar(0) : use blob id's for select queries with BYTE columns
ifx_textasvarchar(1) : return TEXT columns as if they were VARCHAR columns, so that you don't need to use blob id's for select queries.
ifx_byteasvarchar(1) : return BYTE columns as if they were VARCHAR columns, so that you don't need to use blob id's for select queries.
configuration variable : ifx.blobinfile
runtime function :
ifx_blobinfile_mode(0) : return BYTE columns in memory, the blob id lets you get at the contents.
ifx_blobinfile_mode(1) : return BYTE columns in a file, the blob id lets you get at the file name.
If you set ifx_text/byteasvarchar to 1, you can use TEXT and BYTE columns in select queries just like normal (but rather long) VARCHAR fields. Since all strings are "counted" in PHP, this remains "binary safe". It is up to you to handle this correctly. The returned data can contain anything, you are responsible for the contents.
If you set ifx_blobinfile to 1, use the file name returned by ifx_get_blob(..) to get at the blob contents. Note that in this case YOU ARE RESPONSIBLE FOR DELETING THE TEMPORARY FILES CREATED BY INFORMIX when fetching the row. Every new row fetched will create new temporary files for every BYTE column.
The location of the temporary files can be influenced by the environment variable "blobdir", default is "." (the current directory). Something like : putenv(blobdir=tmpblob"); will ease the cleaning up of temp files accidentally left behind (their names all start with "blb").
Automatically trimming "char" (SQLCHAR and SQLNCHAR) data: This can be set with the configuration variable
ifx.charasvarchar : if set to 1 trailing spaces will be automatically trimmed, to save you some "chopping".
NULL values: The configuration variable ifx.nullformat (and the runtime function ifx_nullformat()) when set to true will return NULL columns as the string "NULL", when set to false they return the empty string. This allows you to discriminate between NULL columns and empty columns.
int ifx_connect
([string database [, string userid [, string password]]])
Returns a connection identifier on success, or FALSE on error.
ifx_connect() establishes a connection to an Informix server. All of the arguments are optional, and if they're missing, defaults are taken from values supplied in configuration file (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).
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().
See also ifx_pconnect(), and ifx_close().
Example 1. Connect to a Informix database
|
int ifx_pconnect
([string database [, string userid [, string password]]])
Returns: A positive Informix persistent link identifier on success, or false on error
ifx_pconnect() acts very much like ifx_connect() with two major differences.
This function behaves exactly like ifx_connect() when PHP is not running as an Apache module. 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'.
See also: ifx_connect().
int ifx_close
([int
link_identifier])
Returns: always true.
ifx_close() closes the link to an Informix 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.
ifx_close() will not close persistent links generated by ifx_pconnect().
See also: ifx_connect(), and ifx_pconnect().
Example 1. Closing a Informix connection
|
int ifx_query
(string
query [, int link_identifier [, int cursor_type [, mixed
blobidarray]]])
Returns: A positive Informix result identifier on success, or false on error.
A "result_id" resource used by other functions to retrieve the query results. Sets "affected_rows" for retrieval by the ifx_affected_rows() function.
ifx_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 ifx_connect() was called, and use it.
Executes query on connection conn_id. For "select-type" queries a cursor is declared and opened. The optional cursor_type 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. Non-select queries are "execute immediate". IFX_SCROLL and IFX_HOLD are symbolic constants and as such shouldn't be between quotes. I you omit this parameter the cursor is a normal sequential cursor.
For either query type the number of (estimated or real) affected rows is saved for retrieval by ifx_affected_rows().
If you have BLOB (BYTE or TEXT) columns in an update query, you can add a blobidarray parameter containing the corresponding "blob ids", and you should replace those columns with a "?" in the query text.
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).
See also: ifx_connect().
Example 1. Show all rows of the "orders" table as a html table
|
Example 2. Insert some values into the "catalog" table
|
int ifx_prepare
(string query, int conn_id [, int cursor_def, mixed blobidarray])
Returns a integer result_id for use by ifx_do(). Sets affected_rows for retrieval by the ifx_affected_rows() function.
Prepares query on connection conn_id. For "select-type" queries a cursor is declared and opened. The optional cursor_type 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.
For either query type the estimated number of affected rows is saved for retrieval by ifx_affected_rows().
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.
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).
See also: ifx_do().
int ifx_do
(int
result_id)
Returns TRUE on success, FALSE on error.
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()
See also: ifx_prepare(). There is a example.
string ifx_error
(void);
The Informix error codes (SQLSTATE & SQLCODE) formatted as follows :
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
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. The format of the string is "(char) [SQLSTATE=(two digits) (three digits) SQLCODE=(one digit)]". The first character can be ' ' (space) (success), 'W' (the statement caused some warning), 'E' (an error happened when executing the statement) or 'N' (the statement didn't return any data).
See also: ifx_errormsg()
string ifx_errormsg
([int errorcode])
Returns the Informix error message associated with the most recent Informix error, or, when the optional "errorcode" param is present, the error message corresponding to "errorcode".
See also: ifx_error()
printf("%s\n<br>", ifx_errormsg(-201)); |
int ifx_affected_rows
(int result_id)
result_id is a valid result id returned by ifx_query() or ifx_prepare().
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.
See also: ifx_num_rows()
Example 1. Informix affected rows
|
array ifx_getsqlca
(int result_id)
result_id is a valid result id returned by ifx_query() or ifx_prepare().
Returns a pseudo-row (assiociative array) 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.
Example 1. Retrieve Informix sqlca.sqlerrd[x] values
|
array ifx_fetch_row
(int result_id [, mixed position])
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. Returns FALSE on error
result_id is a valid resultid returned by ifx_query() or ifx_prepare() (select type queries only!).
position is 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.
ifx_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, with the column name as key.
Subsequent calls to ifx_fetch_row() would return the next row in the result set, or false if there are no more rows.
Example 1. Informix fetch rows
|